Category分类可以给已有类进行扩展,主要用于方法函数的补充,却不能补充成员属性。但是可以使用RunTime机制给它加“成员属性”,使用起来很方便哦!
>头文件
#import <UIKit/UIKit.h>
@interface UIButton (UserInfo)
@property (nonatomic, retain) NSDictionary *userInfo;//用于传值,可以包含任何对象足够使用
@property(nonatomic,copy) NSString *nameWithSetterGetter;//字符串
@end
>实现文件
#import "UIButton+UserInfo.h"
#import <objc/runtime.h>
static char *userInfoKey = "userInfoKey";
static NSString *nameWithSetterGetterKey = @"nameWithSetterGetterKey";
@implementation UIButton (UserInfo)
>字典retain
- (void)setUserInfo:(NSDictionary *)userInfo {
objc_setAssociatedObject(self, userInfoKey, userInfo, OS_OBJECT_USE_OBJC_RETAIN_RELEASE);
}
- (NSDictionary *)userInfo {
return objc_getAssociatedObject(self, userInfoKey);
}
>字符串copy
- (void)setNameWithSetterGetter:(NSString *)nameWithSetterGetter {
objc_setAssociatedObject(self, &nameWithSetterGetterKey, nameWithSetterGetter, OBJC_ASSOCIATION_COPY);
}
- (NSString *)nameWithSetterGetter {
return objc_getAssociatedObject(self, &nameWithSetterGetterKey);
}
@end