分类中声明属性
2017-03-01 本文已影响39人
Jessica124
分类(category)
.h中:
@interface <#class name#> (<#category name#>)
@end
.m中:
@implementation <#class#> (<#category name#>)
<#methods#>
@end
这种分类如果声明属性,
@interface ViewController : UIViewController
@property (nonatomic, copy, readonly) NSString *name;
@end
@interface ViewController (Name)
@property (nonatomic, copy) NSString *lastName;
@end
编译器会报警告。
意思是此分类无法生成属性相关实例变量,所以需要开发人员自己在分类中为该属性实现存储方法。
static const void * externVariableKey = "externVariableKey";
@implementation ViewController (Name)
@dynamic lastName;
- (id)lastName {
return objc_getAssociatedObject(self, externVariableKey);
}
- (void)setLastName:(NSString *)lastName {
objc_setAssociatedObject(self, externVariableKey, lastName, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end