面试时碰到几次,类别中如何添加属性。说实话,平时这个几乎不用,也没怎么查过相关文档,对此不甚了解,也就知道匿名类别(即扩展)支持添加属性。
看了下别人写的关于类别中添加属性的博客,好多是利用runtime实现的,个人感觉这种方法也挺简单暴力的。
基本照着别人来的,有些地方稍微改了下:
1.新建一个Person类:
.h文件:
#import <Foundation/Foundation.h>
@interface Person : NSObject
@property (nonatomic, assign) NSInteger age;
- (void)test;
@end
.m文件:
#import "Person.h"
@implementation Person
- (void)test
{
NSLog(@"----");
NSLog(@"%s", __func__);
NSLog(@"----");
}
@end
Person类的类别:
.h文件:
#import "Person.h"
@interface Person (Category)
@property (nonatomic, copy) NSString *name;
- (void)printInfo;
@end
.m文件:
#import "Person+Category.h"
#import <objc/runtime.h>
@implementation Person (Category)
//定义常量 必须是C语言字符串
static char *PersonNameKey = "PersonNameKey";
-(void)setName:(NSString *)name{
/*
OBJC_ASSOCIATION_ASSIGN; //assign策略
OBJC_ASSOCIATION_COPY_NONATOMIC; //copy策略
OBJC_ASSOCIATION_RETAIN_NONATOMIC; // retain策略
OBJC_ASSOCIATION_RETAIN;
OBJC_ASSOCIATION_COPY;
*/
/*
* id object 给哪个对象的属性赋值
const void *key 属性对应的key
id value 设置属性值为value
objc_AssociationPolicy policy 使用的策略,是一个枚举值,和copy,retain,assign是一样的,手机开发一般都选择NONATOMIC
objc_setAssociatedObject(id object, const void *key, id value, objc_AssociationPolicy policy);
*/
objc_setAssociatedObject(self, PersonNameKey, name, OBJC_ASSOCIATION_COPY_NONATOMIC);
}
-(NSString *)name{
return objc_getAssociatedObject(self, PersonNameKey);
}
-(void)printInfo{
NSLog(@"%s----%@-----%@",__func__,self, self.name);
NSLog(@"-------------");
NSLog(@"The file is %s\nThe date is %s\nThe time is %s\nThis is line %d\nThis function is %s", __FILE__, __DATE__, __TIME__, __LINE__, __func__);
}
控制器中调用:
#import "ViewController.h"
#import "Person.h"
#import "Person+Category.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
Person *person = [[Person alloc] init];
person.age = 24;
[person test];
person.name = @"PersonTest";
[person printInfo];
}
打印结果:
2016-06-23 10:40:28.794 Hello[1791:84826] ----
2016-06-23 10:40:28.795 Hello[1791:84826] -[Person test]
2016-06-23 10:40:28.795 Hello[1791:84826] ----
2016-06-23 10:40:28.795 Hello[1791:84826] -[Person(Category) printInfo]----<Person: 0x7ff128f202d0>-----PersonTest
2016-06-23 10:40:28.795 Hello[1791:84826] -------------
2016-06-23 10:40:28.795 Hello[1791:84826] The file is /Users/Desktop/Hello/Hello/Person+Category.m
The date is Jun 23 2016
The time is 10:40:24
This is line 47
This function is -[Person(Category) printInfo]