经常为了类的使用方便,需要为类添加一些附加属性,或者额外的方法。由于iOS的类的存储结构的原因,编译器不会为类别的属性生成默认的get,set方法。因此类别中的属性需要使用动态运行时的方式实现。
类似:
@interface CheckViewController (ToastView)
@property (nonatomic) BOOL hasToastView;
@end
static void *hasToastViewKey = &hasToastViewKey;
static void *activeKey = &activeKey;
@implementation CheckViewController (ToastView)
- (void)setHasToastView:(BOOL)hasToastView_
{
objc_setAssociatedObject(self, &hasToastViewKey, @(hasToastView_), OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
- (BOOL)hasToastView
{
return [objc_getAssociatedObject(self, &hasToastViewKey) boolValue] ? : NO;
}
@end
在swift中对应的实现例子(此处属性为block)
private var DescriptiveName = "handle"
extension UIView {
private var eventHanlerColsure : ()->() {
get {
guard let handler = objc_getAssociatedObject(self, &DescriptiveName) as? ()->() else {
return {()->Void in
};
}
return handler;
}
set(newHandle) {
objc_setAssociatedObject(self, &DescriptiveName, newHandle, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
}
或者
extension UIView {
private struct AssociatedKeys {
static var DescriptiveName = "handle"
}
private var eventHanlerColsure : ()->() {
get {
guard let handler = objc_getAssociatedObject(self, &AssociatedKeys.DescriptiveName) as? ()->() else {
return {()->Void in
};
}
return handler;
}
set(newHandle) {
objc_setAssociatedObject(self, &AssociatedKeys.DescriptiveName, newHandle, objc_AssociationPolicy.OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
}
}
在swift中是为属性声明内联的get,set方法,使用动态运行时绑定的方法与类实现property的关联。此时key必须是const类型的,编译期生成标志不变,程序运行期间,key值地址不能发生变化,因此可以使用以上两种方式定key值。
网友评论