版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_18683985/article/details/82432810
我们可以通过runtime来给iOS的分类添加属性.
想添加属性,记住几个关键词,1.@dynamic 2.Associated
1. 首先我们像普通的类一样在.h里头使用@property声明一个属性
///xxx+CH.h.这里是xxx类的CH分类的.h文件
@interface xxx (CH)
@property (nonatomic ,strong) NSString *name;
@end
这时,.m中就会出现两个警告
Property 'name' requires method 'name' to be defined - use @dynamic or provide a method implementation in this category
Property 'name' requires method 'setName:' to be defined - use @dynamic or provide a method implementation in this category
这时.我们在.m中使用@dynamic修饰一下这个属性名字就没有警告了.
//xxx+CH.m
@implementation xxx (CH)
@dynamic name;
@end
2.使用runtime的方法动态绑定属性.(“重写”get-set方法)
///1.
//xxx+CH.m
#import <objc/runtime.h>///记得别忘记导入objc/runtime.h
@implementation xxx (CH)
@dynamic name;
/// name的key
static char *nameKey = "nameKey";
- (void)setName:(NSString *)name {
objc_setAssociatedObject(self, nameKey, name, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (NSString *)name {
id name = objc_getAssociatedObject(self, nameKey);
if (name) {
return name;
} else {
return @"";
}
}
@end
到此为止,我们就给分类添加好属性了.
注意点:
1.对象有哪些类型
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. */
};
2.非对象类型的取值.我们可以使用id的getValue来去取值去返回.
例: 这里我们取一个CGRect值
- (CGRect)rect {
id rectResult = objc_getAssociatedObject(self, rectKey);
if (rect) {
CGRect rect;
[rectResult getValue:&rect];
return rect;
} else {
return CGRectZero;
}
}