一、增加新技能篇
TridonLee要通過Category和Associated Objects增加技能了归露,快看!
創(chuàng)建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
{
//設(shè)置關(guān)聯(lián)對象
objc_setAssociatedObject(self,@selector(associatedBust), associatedBust,OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
-(NSNumber*)associatedBust
{
//得到關(guān)聯(lián)對象
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;
}
這次運行結(jié)果多出了一個associatedBust(胸圍)和一個associatedCallBack(寫代碼)屬性苹粟。
如圖:
我們成功的給TridonLee添加個一個胸圍的屬性和一個寫代碼的回調(diào),但是添加屬性沒有什么意義跃闹,我們平時在開發(fā)過成功中用的比較多的就是添加回調(diào)了嵌削。
Demo傳送門-> 5.1 增加新功能篇Demo