在Category中添加成員變量
.h文件
@interface UIView (UIViewHelp)
@property (nonatomic,copy)NSString *name;
@end
.m文件
//特別注意要導入runtime包才可以對category的成員變量實現set和get方法提供中間橋梁
#import <objc/objc-runtime.h>
@implementation UIView (UIViewHelp)
- (void)setName:(NSString *)name{
objc_setAssociatedObject(self, "kname", name, OBJC_ASSOCIATION_COPY);
}
- (NSString *)name{
NSString* _name = (NSString*)objc_getAssociatedObject(self, "kname");
return _name;
}
@end
擴展(與swift的擴展完全不同,只是名字一樣而已)
一般用于文件中定義私有變量
@interface ViewController ()
{
NSInteger _count;
}
@end