簡體   English   中英

了解引用計數/內存和屬性

[英]Understanding reference counting/memory and properties

我的問題是-如果我錯了,請您指正我嗎? 謝謝!

我能想到的最簡單的示例是從頭開始創建應用程序。 刪除MainWindow nib文件等。

// .h file of appDelegate
UIWindow* window_;

@property UIWindow* window;

// .m appDelegate
@synthesize window = window_
[window_ release] // dealloc method

可以說在Application中確實完成了啟動方法

{
// window is currently nil with a reference count of 0.

window_ [[UIWindow alloc] initWithFrame: [[UIScreen mainScreen] bounds]]; // window_ has a reference count of 1

MyViewController* myVC = [[MyViewController alloc] initWithNibName:nil bundle nil]; // myVC has a reference count of 1

UINavigationController* navCon = [[UINavigationController alloc] initWithRootViewController:myVC] // navCon reference count 1, myVC reference count of 2

//way 1
self.window.rootViewController = navCon; // navcon has a reference count still 1. however since self.window.rootViewController was nill, all is nice and dandy. if however, self.window.rootViewController was not nil there would be a memory leak
[myVC release]; // brings myVC down to 1, all is good and well;
[self.window makeKeyAndVisible];

//way 2
[self.window setRootViewController: navCon]; // releases self.window setRootViewController 1 to 0, then retains navController which brings it back to 1
[myVCrelease]; //onece again brought back to one
[navCon release]; //since it's reference count is 2 thanks to setRootViewController
[self.window.makeKeyAndVisible].
}

navCon最終何時發布? 該應用何時關閉? 還是幕后發生了什么? 我的編程方式是否與您的風格類似? 我應該使用很多self.window而不是window_嗎? 我應該使用很多setProperty而不是=嗎? 感謝您的時間!

}

幾點:

當與對象關聯的保留計數達到零時,立即釋放對象。

屬性處理保留和釋放,絕對應該使用屬性而不是與之關聯的原始變量(使用self.window而不是_window)。

不要試圖跟蹤原始計數,而要負責任地管理內存。 因此,例如,只要將myVC移交給導航控制器,就可以釋放它,而不是在保留計數增加時釋放。

如果您只是自動釋放而不是手動釋放,則對您來說也將更加容易。 不必擔心。 autorelease非常簡單,它只是將release稱為“稍后”,實際上是再次執行run循環時。 基本上,它使您可以更加關注代碼,而不必關心內存管理。 到區塊末尾,其他任何未保留的內容都將為您釋放。

這也遵循Google針對目標C提出的標准。請參見http://google-styleguide.googlecode.com/svn/trunk/objcguide.xml

我將在導航控制器初始化后立即發布myVC

UINavigationController* navCon = [[UINavigationController alloc] initWithRootViewController:myVC]
[myVC release];

第一種方式是泄漏navCon

我喜歡第二種方式。

您應該始終使用屬性。

ivar管理

所有的ivars應該使用屬性創建。 如果ivar僅用於本地類,則應在class extension聲明它。

所有屬性都應使用帶下划線的陰影ivars進行合成。

所有IBOutlets應該具有retain屬性。

所有BOOL屬性都應具有is * getter。

應該assign所有delegate屬性(如果在ARC下則為weak )。

例子:

@property (nonatomic, retain) NSString *exampleString;
@property (nonatomic, retain) IBOutlet UILabel *exampleLabel;
@property (nonatomic, assign, getter=isExampleBool) BOOL exampleBool;

@synthesize exampleString = _exampleString;
@synthesize exampleLabel = _exampleLabel;
@synthesize exampleBool = _exampleBool;

init, dealloc, viewDidUnload

init方法中

  • 屬性值應該直接設置,而不是通過屬性設置。

  • 應該設置或創建任何不應默認為nil,0或NO的ivars。

dealloc方法中:

  • 應該釋放所有ivar對象,而不是通過屬性將其值設置為nil

  • 所有委托對象都應設置為nil。

viewDidUnload

  • 所有IBOutlets都應釋放並設置為nil。

暫無
暫無

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

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