類別
對(duì)于 iOS 開發(fā)者來(lái)說(shuō),對(duì)于類別肯定不陌生,在 OC 的API 中有很多的類都有自己的類別,既然如此,那么類別有哪些優(yōu)點(diǎn)呢?
- 對(duì)現(xiàn)有類功能進(jìn)行擴(kuò)展;
- 分散類的實(shí)現(xiàn);
- 對(duì)類中的方法歸類,方便查閱、更新和維護(hù);
該類別添加方法
這個(gè)就不用多說(shuō)了,是個(gè)人都會(huì)。
給類別添加屬性
在我們學(xué)習(xí) OC 的時(shí)候,一般都是說(shuō)是不能給類別添加屬性的(這種太絕對(duì)的說(shuō)法你相信嗎),那么到底能不能給類別添加方法呢?答案當(dāng)然是肯定的,就是能給類別添加屬性。
給類別添加屬性有兩種情況下是可以的:
給類別添加只讀屬性,同時(shí)實(shí)現(xiàn)
getter
方法。
@property (nonatomic, readonly) NSUInteger count;
- (NSUInteger)count {
return self.length;
}-
使用 OC 的運(yùn)行時(shí)關(guān)聯(lián)特性,實(shí)現(xiàn)
setter
和getter
方法。
@property (nonatomic, strong) NSString *name;
NSString * const kName = @"Name";
- (void)setName:(NSString *)name {
objc_setAssociatedObject(self, (__bridge const void *)(kName), name, OBJC_ASSOCIATION_COPY);
}- (NSString *)name { return objc_getAssociatedObject(self, (__bridge const void *)(kName)); }
對(duì)于這里設(shè)置的屬性 policy,對(duì)應(yīng)設(shè)置屬性時(shí)的 strong
、copy
、assign
、nonatomic
typedef OBJC_ENUM(uintptr_t, objc_AssociationPolicy) {
OBJC_ASSOCIATION_ASSIGN = 0, /< Specifies a weak reference to the associated object. /
OBJC_ASSOCIATION_RETAIN_NONATOMIC = 1, /< Specifies a strong reference to the associated object.
* The association is not made atomically. /
OBJC_ASSOCIATION_COPY_NONATOMIC = 3, /< Specifies that the associated object is copied.
* The association is not made atomically. /
OBJC_ASSOCIATION_RETAIN = 01401, /< Specifies a strong reference to the associated object.
* The association is made atomically. /
OBJC_ASSOCIATION_COPY = 01403 /< Specifies that the associated object is copied.
* The association is made atomically. */
};
Demo
Demo 請(qǐng)戳 這里