iOS-关联属性Associate
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]
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。