iOS分类用的比较多,基本都是扩展方法,如果想要扩展属性,就要用到runtime了,使用
objc_getAssociatedObject
objc_setAssociatedObject
上代码:给Test新建一个分类,关联一个属性name;
#import "Test.h"
#import "Property.h"
@interface Test (pp)
@property(nonatomic ,
strong) Property* name;
@end
#import "Test+pp.h"
#import <objc/runtime.h>
static char* NAME;
@implementation Test (pp)
- (Property *)name{
return
objc_getAssociatedObject(self,
NAME);
}
- (void)setName:(Property *)name{
objc_setAssociatedObject(self,
NAME, name,
OBJC_ASSOCIATION_COPY_NONATOMIC);
}
@end
注意因为用的是copy,所以Property类要遵守NSCopying协议。
在外部使用:
Property* two = [Property
new];
test.name = two;
内存释放会不会有问题?
#import "Property.h"
@implementation Property
-(void)dealloc{
NSLog(@"%s",__FUNCTION__);
}
- (id)copyWithZone:(NSZone *)zone{
Property* pro = [Property
allocWithZone:zone];
return pro;
}
@end
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary
*)launchOptions
{
self.array = [NSMutableArray
array];
Property* pro = [[Property
alloc]
init];
Test* test = [Test
new];
test.name = pro;
Property* two = [Property
new];
test.name = two;
[self.array
addObject:pro];
[self.array
addObject:two];
return
YES;
}
输入打印结果:
2015-02-27 23:43:51.816 PNChartDemo[1486:40966] -[Property dealloc]
2015-02-27 23:43:51.816 PNChartDemo[1486:40966] -[Property dealloc]
pro和two都在数组中,自动释放的就是test中关联的copy那一份,test.name = two会释放[pro copy],test自动释放的时候会释放two.copy
由此可见关联的引用会在实例释放时,自动释放的。