码迷,mamicode.com
首页 > 移动开发 > 详细

iOS-关联属性Associate

时间:2015-02-28 08:55:03      阅读:203      评论:0      收藏:0      [点我收藏+]

标签:associate   runtime   

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

由此可见关联的引用会在实例释放时,自动释放的。







iOS-关联属性Associate

标签:associate   runtime   

原文地址:http://blog.csdn.net/growinggiant/article/details/43975199

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!