Objective-C Runtime技术调研(五)
一、增加新技能篇
TridonLee要通过Category和Associated Objects增加技能了,快看!
创建TLPeople+Associated.h文件如下:
#import"TLPeople.h"
typedefvoid(^CodingCallBack)();
@interfaceTLPeople (Associated)
@property(nonatomic,strong)NSNumber*associatedBust;//胸围
@property(nonatomic,copy)CodingCallBackassociatedCallBack;//写代码
@end
TLPeople+Associated.m如下:
#import"TLPeople+Associated.h"
#if TARGET_IPHONE_SIMULATOR
#import <objc/objc-runtime.h>
#else
#import <objc/runtime.h>
#import <objc/message.h>
#endif
@implementationTLPeople (Associated)
-(void)setAssociatedBust:(NSNumber*)associatedBust
{
//设置关联对象
objc_setAssociatedObject(self,@selector(associatedBust), associatedBust,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSNumber*)associatedBust
{
//得到关联对象
returnobjc_getAssociatedObject(self,@selector(associatedBust));
}
-(void)setAssociatedCallBack:(CodingCallBack)associatedCallBack
{
objc_setAssociatedObject(self,@selector(associatedCallBack), associatedCallBack,OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(CodingCallBack)associatedCallBack
{
returnobjc_getAssociatedObject(self,@selector(associatedCallBack));
}
@end
在main.m中运行以下代码
#import <Foundation/Foundation.h>
#import "TLPeople.h"
#import "TLPeople+Associated.h"
int main(intargc,constchar* argv[]) {
@autoreleasepool{
TLPeople*tlTeacher = [[TLPeoplealloc]init];
tlTeacher.name=@"TridonLee";
tlTeacher.age=18;
[tlTeachersetValue:@"Teacher"forKey:@"occupation"];
tlTeacher.associatedBust=@(90);
tlTeacher.associatedCallBack= ^(){
NSLog(@"TridonLee Teacher要写代码了!");
};
tlTeacher.associatedCallBack();
NSDictionary*propertyResultDic = [tlTeacherallProperties];
for(NSString*propertyNameinpropertyResultDic.allKeys) {
NSLog(@"propertyName:%@, propertyValue:%@",propertyName, propertyResultDic[propertyName]);
}
NSDictionary*methodResultDic = [tlTeacherallMethods];
for(NSString*methodNameinmethodResultDic.allKeys) {
NSLog(@"methodName:%@, argumentsCount:%@", methodName, methodResultDic[methodName]);
}
}
return0;
}
这次运行结果多出了一个associatedBust(胸围)和一个associatedCallBack(写代码)属性。
如图:
![](https://img.haomeiwen.com/i2022462/e43d0f56e8e0a740.png)
我们成功的给TridonLee添加个一个胸围的属性和一个写代码的回调,但是添加属性没有什么意义,我们平时在开发过成功中用的比较多的就是添加回调了。
Demo传送门-> 5.1 增加新功能篇Demo