4. 动态添加方法

这一点上有两点要表达一下:第一,XCode运行你在Category的.h文件申明@Property,编译通过,但运行时如果没有Runtime处理,进行赋值取值,就马上报错。第二,这一点是iOS面试当中经常面到的问题:如何给扩展添加属性?。

1)Sense:

Teacher: What's your Chinese name?

XiaoMing: I have no one.

LiHua: You should have one.

LiHua: Your Chinese name is __

在程序当中,假设XiaoMing的中没有chineseName这个属性,后来被Runtime添加一个名字叫chineseName的属性。那么,Runtime是如何做到的呢?

2)Step:

①申明chineseName属性

#import "XiaoMing.h"

@interface XiaoMing (MutipleName)

@property(nonatomic,copy) NSString *chineseName;

@end

②动态添加属性和实现方法

#import "XiaoMing+MutipleName.h"

#import

@implementation XiaoMing (MutipleName)

char cName;

-(void)setChineseName:(NSString *) chineseName{

objc_setAssociatedObject(self, &cName, chineseName, OBJC_ASSOCIATION_COPY_NONATOMIC);

}

-(NSString *)chineseName{

return objc_getAssociatedObject(self, &cName);

}

@end

③使用chineseName属性

-(void)answer{

NSLog(@"My Chinese name is %@",self.xiaoMing.chineseName);

self.chineseNameTf.text = self.xiaoMing.chineseName;

}

你可能感兴趣的:(4. 动态添加方法)