1>.methods1
直接在category的.h中添加揩徊,這時xcode會有warning。
Property 'test1' requires method 'test1' to be defined - use @dynamic or provide a method implementation in this category
按照提示在.m文件在@dynamic關(guān)鍵字修改就OK了。dynamic在編譯時不會檢查setter/getter的實(shí)現(xiàn)嘀掸,在運(yùn)行時setter/getter會動態(tài)綁定涯竟,在需要setter/getter的class中自己實(shí)現(xiàn)就OK了。
#import <Foundation/Foundation.h>
@interface NSObject (AddProperty1)
@property(nonatomic,strong)NSString *test1;
@end
----------------------------------------------------------------------
#import "NSObject+AddProperty1.h"
@implementation NSObject (AddProperty1)
@dynamic test1;
@end
(在用這種方法添加proprety卸奉,使用setter/getter的class如果不implementation會crash的)
2>.methods2
//只用在.h文件添加協(xié)議
#import <Foundation/Foundation.h>
@protocol NSObjectProtocol <NSObject>
@optional
@property(nonatomic,strong)NSString *test3;
@end
@interface NSObject (AddProperty3)<NSObjectProtocol>
@end
同上一種方法一樣钝诚,在使用setter/getter的class中要implementation,否則會crash
3>.methods3
#import <Foundation/Foundation.h>
@interface NSObject (AddProperty2)
@property(nonatomic,strong)NSString *test2;
@end
----------------------------------------------------------------------
#import "NSObject+AddProperty2.h"
#import <objc/runtime.h>
@implementation NSObject (AddProperty2)
-(NSString*)test2{
return objc_getAssociatedObject(self, @selector(test2));
}
-(void)setTest2:(NSString *)test2{
objc_setAssociatedObject(self, @selector(test2), test2, OBJC_ASSOCIATION_RETAIN_NONATOMIC);
}
@end
利用objctive-c的runtime特性择卦。個人更偏好于第三種方法敲长,改動最小,而且在不知道源碼的源碼的情況下也能add property
附上Demo省得以后自己忘記了
參考:https://www.cnblogs.com/starer/p/3813674.html
————————————————
希望后人珍惜時間秉继,少走彎路祈噪,享受生活。
VKOOY