-
OC
的分类允许给分类添加属性,但不会自动生成setter和getter,可通过运行时建立关联引用,添加一个title属性,如下:
@interface MyClass (Category)
@property (nonatomic, assign) NSString *title;
@end
static void *key = &key;
@implementation MyClass (Category)
- (void)setTitle:(NSString *)title {
objc_setAssociatedObject(self, & key, title, OBJC_ASSOCIATION_COPY);
}
-(NSString *)title {
return objc_getAssociatedObject(self, &key);
}
@end
-
OC
中分类添加属性的情况,在swift中也存在,那么我们看看swift中的实现:
// MyClassExtension.swift
class MyClass {
}
private var key: Void?
extension MyClass {
var title: String? {
get {
return objc_getAssociatedObject(self, &key) as? String
}
set {
objc_setAssociatedObject(self,
&key, newValue,
.OBJC_ASSOCIATION_COPY_NONATOMIC)
}
}
}