iOS為類別新增屬性的方法(RunTime)
一般認為Category不能新增變數,其實系統已經告訴我們是可以的.
這傢伙已經給UIViewController添加了圖中的幾個屬性,那麼如何實現?
其實是使用@dynamic來動態新增的。 (即執行時Runtime)
程式碼:
1.建立Person類
#import <Foundation/Foundation.h>
@interface Person :NSObject
@property (nonatomic,copy)NSString * name;
@end
2.建立Person的類別
#import "Person.h"
// 新增額外兩個屬性
@interface
@property (nonatomic,assign)NSInteger age;
@property (nonatomic,copy)NSString * stu;
@end
3.Person類別.m的實現
#import "Person+addProperty.h"
#import <objc/runtime.h>
@implementation Person (addProperty)
staticchar nameKey = 'n';
staticchar stuKey = 's';
// 給age屬性提供getter和
- (NSInteger)age{
return [objc_getAssociatedObject(self, &nameKey)integerValue];
}
- (void)setAge:(NSInteger)age {
NSString * s = [NSStringstringWithFormat:@"%ld",(long)age];
objc_setAssociatedObject(self, &nameKey,s,OBJC_ASSOCIATION_COPY_NONATOMIC);
}
// 給stu屬性提供getter和setter方法
- (NSString*)stu{
returnobjc_getAssociatedObject(self, &stuKey);
}
- (void)setStu:(NSString *)stu{
objc_setAssociatedObject(self, &stuKey, stu,OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
4.用一下吧
#import "ViewController.h"
#import "Person+addProperty.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[superviewDidLoad];
Person * p = [[Personalloc] init];
p.name =@"原有屬性";
p.stu =@"新增的屬性";
p.age =17;
NSLog(@"%@ %@ %ld",p.name,p.stu,p.age);
}