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

上一篇下一篇

猜你喜欢

热点阅读