美文网首页
iOS为类别添加属性的方法(RunTime)

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

作者: 皮皮瑞 | 来源:发表于2017-04-13 18:42 被阅读0次

一般认为Category不能添加变量,其实系统已经告诉我们是可以的.

这家伙已经给UIViewController添加了图中的几个属性,那么如何实现?

其实是使用@dynamic来动态添加的。 (即运行时Runtime)

代码:

1.创建Person类

#import

@interfacePerson :NSObject

@property(nonatomic,copy)NSString* name;

@end

2.创建Person的类别

#import"Person.h"

//添加额外两个属性

@interfacePerson (addProperty)

@property(nonatomic,assign)NSIntegerage;

@property(nonatomic,copy)NSString* stu;

@end

3.Person类别.m的实现

#import"Person+addProperty.h"

#import

@implementationPerson (addProperty)

staticcharnameKey ='n';

staticcharstuKey ='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"

@interfaceViewController()

@end

@implementationViewController

- (void)viewDidLoad {

[superviewDidLoad];

Person* p = [[Personalloc]init];

p.name=@"原有属性";

p.stu=@"添加的属性";

p.age=17;

NSLog(@"%@ %@ %ld",p.name,p.stu,p.age);

}

相关文章

网友评论

      本文标题: iOS为类别添加属性的方法(RunTime)

      本文链接:https://www.haomeiwen.com/subject/ypfiattx.html