簡體   English   中英

Objective-C屬性參考計數

[英]Objective-C property reference count

有人可以幫助我了解Objective C屬性中的引用計數。

假設我上課

@interface TA : NSObject
{
    TB* tb;
}
- (id) init;
- (void) dealloc;
@property (nonatomic,retain) TB* tb;
@end

@implementation
@synthesize tb;
- (id) init {...}
- (void) dealloc {...}
@end

我的理解是將新值分配給“ tb”,例如“ ta.tb = newValue”等效於以下邏輯:

if (newValue != oldValue)
{
    [newValue retain];
    [oldValue release];
    tb_storage_cell = newValue;
}

但是它如何在init方法中工作?

[TA alloc]是否用零預初始化實例內存?

我需要在init中執行tb = nil嗎?

如果alloc確實使用零預初始化了內存,則由於初始化 tb已經為nil,因此在初始化過程中不需要設置tb = nil。 那正確嗎?

另一方面,如果alloc不會將分配的內存清零,並且其中包含垃圾,那么設置程序嘗試在初始化分配中釋放舊值將失敗,並且可能永遠無法工作。 那么,這是否意味着alloc確實可以保證返回總是歸零的內存塊?

接下來,進行dealloc

假定序列在dealloc內部是:

[tb release];
tb = nil;
[super dealloc];

那正確嗎?

但是,如果是這樣,它又如何工作? 首次發行應該發行“ tb”。 然后,賦值“ tb = nil”應該再次釋放tb的oldValue,因此它應該等於兩次釋放並崩潰。

還是我應該在dealloc中跳過“ [tb release]”,然后簡單地執行

tb = nil;
[super dealloc];

Objective-C規范明確指出,所有對象實例在分配時都將其成員清零。

僅當您使用instance.property語法時,才調用屬性的get和set方法。 您的“ tb = nil”行只是將實例變量的值設置為nil,而不是調用該屬性。

您必須執行self.tb = nil才能調用屬性設置器。 在dealloc方法中釋放值時,通常應始終使用屬性語法。

self.tb = nil;

這將正確釋放並清除該屬性。

您可以將方法編寫為:

-(id) init{
if(self=[super init]){
tb = [[TB alloc] initWithSomething];
}
return self;
}

- (void) dealloc{
[tb release];
[super dealloc];
}
- (void) someMethod{
NSLog(@"This is ok since tb is always initialized. %@", [tb description]);
NSLog(@"This is also ok. %@", [tb description]);
}

這是典型的初始化,或者,如果您認為不必從開始處初始化tb,則可以使其變得懶惰:

-(tb) tb{
if (!tb)
   tb = [[TB alloc] initWithSomething];
return tb
}

 -(id) init{
    self=[super init];
    return self;
    }

- (void) dealloc{
[tb release];
[super dealloc];
}
- (void) someMethod{
NSLog(@"This might be not ok, tb is not necessarily initialized:%@ ", [tb description]);
NSLog(@"This is ok since tb is always initialized by the getter. %@", [self.tb description]);
}

這樣,除非您在代碼的其他部分進行了初始化,否則必須使用屬性調用tb以確保已初始化。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM