首先说明一下,直接在Category中是不能添加属性的,那么我们怎么样才能不使用集成就可以添加属性呢!
我们就要用到Runtime的知识了!
不多说,直接上代码
1: 在.h 和.m 文件中写下如下代码
#import <UIKit/UIKit.h>
@interface UIButton (nature)
@property (copy, nonatomic) NSString *isSelect;
@end
#import "UIButton+nature.h"
#import <objc/runtime.h>
@implementation UIButton (nature)
- (void)setIsSelect:(NSString *)isSelect{
objc_setAssociatedObject(self, @selector(isSelect), isSelect, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
- (NSString *)isSelect{
return objc_getAssociatedObject(self, _cmd);
}
2:打印下结果
UIButton *btn = [UIButton new];
btn.isSelect = @"yes";
NSLog(@"isSelect = %@",btn.isSelect);
2015-08-13 09:48:12.954 Runtime[984:38562] isSelect = yes