您的位置:首页 > 移动开发 > IOS开发

iOS为类别添加属性的方法(RunTime)

2016-04-15 14:35 489 查看
一般认为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 Person (addProperty)

@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和setter方法

- (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);
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: