1.@selector原理介紹
SEL 類成員方法的指針
可以理解 @selector()就是取類方法的編號(hào),他的行為基本可以等同C語言的中函數(shù)指針,只不過C語言中,可以把函數(shù)名直接賦給一個(gè)函數(shù)指針昌粤,而Object-C的類不能直接應(yīng)用函數(shù)指針苔可,這樣只能做一個(gè)@selector語法來取.
它的結(jié)果是一個(gè)SEL類型缴挖。這個(gè)類型本質(zhì)是類方法的編號(hào)(函數(shù)地址)
2.使用@selector方法地址作為分類屬性標(biāo)識(shí)符
@interface NSObject (CategoryWithProperty)
@property (nonatomic, strong) NSObject *property;
@end
@implementation NSObject (CategoryWithProperty)
- (NSObject *)property {
return objc_getAssociatedObject(self, @selector(property));
}
- (void)setProperty:(NSObject *)value {
objc_setAssociatedObject(self, @selector(property), value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
3. 使用方法_cmd作為分類屬性標(biāo)識(shí)符
@interface NSObject (CategoryWithProperty)
@property (nonatomic, strong) NSObject *property;
@end
@implementation NSObject (CategoryWithProperty)
- (NSObject *)property {
return objc_getAssociatedObject(self, _cmd);
}
- (void)setProperty:(NSObject *)value {
objc_setAssociatedObject(self, _cmd, value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end