理论上category不能声明私有变量,但通过另一种手法,间接实现这样的功能。
.h
import <UIKit/UIKit.h>
@interface UIView (Test)
@property (nonatomic,copy) NSString *name;
@end
.m
import "UIView+Test.h"
import <objc/runtime.h>
@implementation UIView (Test)
-
(NSString *)name {
return objc_getAssociatedObject(self, @selector(name));
}
- (void)setName:(NSString *)value {
objc_setAssociatedObject(self, @selector(name),value, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
网友评论