这是我为补充我写的博客文章而提供的源代码。
通过在这个 NSObject
分类中定义的方法,您可以简化您自己的分类中属性的实现。
只需将 NSObject+DZLCategoryProperties
添加到您的项目中,并在您已声明属性的任何分类中。
如果您有一个类似以下示例的分类接口
@interface Person (XYZAdditions)
@property (strong, nonatomic) NSString *xyz_nickname;
@property (strong, nonatomic) Company *xyz_employer;
@end
只需将属性声明为动态,并在运行时从该 NSObject+DZLCategoryProperties
分类中的某个方法调用以实现属性的获取器和设置器。
@implementation Person (XYZAdditions)
@dynamic nickname;
@dynamic employer;
+ (void)load
{
// implement for all properties (where methods are not already defined)
[self DZL_implementDynamicPropertyAccessors];
// or implement only for specific property specified by name
[self DZL_implementDynamicPropertyAccessorsForPropertyName:@"xyz_nickname"];
// or implement only for specific properties matching regular expression
[self DZL_implementDynamicPropertyAccessorsForPropertyMatching:@"^xyz_"];
}
@end
为了利用上述方法的简写版本,请在项目的预编译头中定义 DZL_CP_SHORTHAND
,例如
在 MyAwesomeApp-Prefix.pch
#define DZL_CP_SHORTHAND
这允许您使用以下简写方法
+[NSObject implementDynamicPropertyAccessors]
+[NSObject implementDynamicPropertyAccessorsForPropertyName:]
+[NSObject implementDynamicPropertyAccessorsForPropertyMatching:]
通常,您可能如下在分类中定义一个简单的对象类型属性
@interface UIView (DZLAdditions)
@property (strong, nonatomic) NSString *name;
@end
static const void *nameKey = &nameKey;
@implementation UIView (DZLAdditions)
- (NSString *)name
{
return objc_getAssociatedObject(self, nameKey);
}
- (void)setName:(NSString *)name
{
objc_setAssociatedObject(self, nameKey, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
如果您添加多个属性,您必须为每个属性定义获取器和设置器。最糟糕的是,所有这些获取器和设置器看起来几乎完全相同。
将 NSObject+DZLCategoryProperties
目录添加到您的项目中,并在您的项目的预编译头文件中可选地定义 DZL_CP_SHORTHAND
如果您喜欢这个项目,为什么不在推特上关注我呢?