[英]Effect of 'myObj = [[[[MyClass alloc] init] autorelease] retain];'?
我剛剛下載了Facebook iOS SDK ,我注意到在SDK附帶的示例代碼中,只要它創建了一個Facebook類的實例,它就像這樣:
_facebook = [[[[Facebook alloc] init] autorelease] retain];
其中_facebook
是調用對象的成員變量(即不是局部變量)。
任何人都可以確切地解釋自動釋放然后保留它的重點是什么?
除了消耗一些周期和內存之外,它實際上沒有做任
或者,更確切地說,在正確編寫的應用程序中,它什么都不做。 在錯誤編寫的應用程序中,它可能會通過延長_facebook
對象的生命周期來掩蓋錯誤。 但是,這不是一個真正的解決方案。
我在http://github.com/facebook/facebook-ios-sdk/blob/master/sample/DemoApp/Classes/DemoAppViewController.m中找到了類似的代碼行。如果這就是你所指的那個,是的,它是胡說八道。
雖然你發現的代碼可能只是草率,但這種模式有意義。
“alloc,autorelease,retain”意味着該對象在兩個地方被引用:
如果兩個引用可以獨立發布,這很重要。 例如,如果SDK可以在調用堆棧完成之前釋放其引用並耗盡自動釋放池。 好的,這非常微妙; 我的意思是什么?
考慮這些情況:
A)實際代碼
_facebook = [[[[Facebook alloc] init] autorelease] retain];
B)提出的簡單“替代”(非等效)
_facebook = [[Facebook alloc] init];
為什么這很重要? 想象一下這樣的代碼:
@implementation (Thinger)
+(id) make_new_thing
{
return my_copy_of_thing = [[[[Thing alloc] init] autorelease] retain];
}
+(id) forget_about_thing
{
if (my_copy_of_thing != nil) {
[my_copy_of_thing release];
my_copy_of_thing = nil;
}
}
@end
void foo() {
NSAutoreleasePool* pool = [[NSAutoreleasePool alloc] init];
id thing = [Thinger make_new_thing];
[Thinger forget_about_thing];
...
[thing useThing]; // implementation B would break here !
[pool drain];
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.