category添加属性
2016-05-06 本文已影响61人
json_jie
// key作为该对象实例的属性的键,而value就是对象实例的属性的值
// associative是在运行时动态的添加属性
UIView+AddProperty.h
import <UIKit/UIKit.h>
@interface UIView (AddProperty)
@property(nonatomic,copy)NSString *title;
@end
UIView+AddProperty.m
import "UIView+AddProperty.h"
import <objc/runtime.h>
@implementation UIView (AddProperty)
static void *MyKey = (void *)@"son";
// Obj-c中的外联方法
// OBJC_EXPORT id objc_getAssociatedObject(id object, const void *key)
// OBJC_EXPORT void objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy)
-(NSString *)title
{
return objc_getAssociatedObject(self, MyKey);
}
-(void)setTitle:(NSString *)title
{
objc_setAssociatedObject(self, MyKey, title, OBJC_ASSOCIATION_COPY);
}
@end
//调用
import "UIView+AddProperty.h"
import <objc/runtime.h>
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
UIView *view = [[UIView alloc] initWithFrame:CGRectMake(100, 150, 100, 100)];
view.backgroundColor = [UIColor redColor];
[self.view addSubview:view];
view.title = @"哈喽 json category 添加属性";
NSLog(@"%@",view.title);
// category添加属性[16959:1926914] 哈喽 json category 添加属性
}