iOS-關聯屬性Associate

來源:互聯網
上載者:User

標籤: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 = [Propertynew];

test.name = two;


記憶體釋放會不會有問題?

#import "Property.h"


@implementation Property

-(void)dealloc{

    NSLog(@"%s",__FUNCTION__);

}

- (id)copyWithZone:(NSZone *)zone{

   Property* pro  = [PropertyallocWithZone:zone];

   return pro;

}

@end



- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

{

    self.array = [NSMutableArrayarray];

   Property* pro = [[Propertyalloc] init];

   Test* test = [Testnew];

    test.name = pro;

    

   Property* two = [Propertynew];

    test.name = two;

    [self.arrayaddObject:pro];

    [self.arrayaddObject:two];


    returnYES;

}


輸入列印結果:

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.