[英]What is the difference between these two ways of allocating memory in Objective-C?
[英]Objective C: Allocating Memory
我是Objective C的新手,這是我的困惑:
什么時候適用於為實例分配內存? 像這樣:
什么時候適用於此......
NSString *str = [[NSString alloc]init];
並使用這...
- (NSString *) formatStr:(NSString *) str{
NSString *str = (NSString *) str;
...
.....
.......
}
甚至創建UIActionSheet,它使用alloc,但在其他UI元素中,它不會..
究竟是什么原因以及何時完成?
謝謝fellas ..:D
除了“正常”分配路由(即通過[[MyClass alloc] init]
),一些類提供了所謂的“工廠方法”。 這些是在內部分配對象的類方法。 使用工廠方法的優點是它們可以創建一個合適的子類來返回調用者。 但是,在這兩種情況下,分配最終都是通過alloc/init
完成的。
Objective C的alloc方法處理分配內存,您不必擔心分配,只需管理保留和釋放周期。
checkout 關於Apple的Memory Management文章
當你使用alloc + init創建一個實例時,或者通過名稱中包含init的方法獲得一個實例(一個約定,例如initWithString)你被認為擁有該對象,這就是你不能保留它(它的ref計數器)已經設置為1)並且需要在完成后最終釋放它。 當你通過調用名稱中沒有獲取init的方法接收實例時(拇指規則,但你應該總是檢查文檔),這意味着你不是對象的所有者,即對象可能隨時被釋放,即使你正在使用它。 通常,諸如stringWithFormat
方法將返回自動釋放的對象,這些對象將一直存在,直到事件周期結束(除非您通過在字符串上調用retain來聲明所有權)。 我強烈建議閱讀可可內存管理指南。
NSString *str = [[NSString alloc]init]; //you own the object pointed to by str. Its retain count is 1. If you don't call release this will be a memory leak.
- (NSString *) formatStr:(NSString *) str{
NSString *str = (NSString *) str; //you don't own str. btw, you don't need casting here
//using str here might throw exception if its owner has released it
[str retain]; //you own str now. you can do whatever you want with it. It's yours
.......
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.