值得一提這裏的Cocoa Memory Management Rules。如果您在非GC環境中工作,例如iPhone,它總是值得一提的。
基本規則狀態:
You take ownership of an object if you create it using a method whose name begins with 「alloc」 or 「new」 or contains 「copy」 (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.
顯然沒有用ALLOC,新...什麼的含副本獲得的obj。所以你不擁有它。
在你的代碼中,推論的第二個也是相關的:
A received object is normally guaranteed to remain valid within the method it was received in (exceptions include multithreaded applications and some Distributed Objects situations, although you must also take care if you modify an object from which you received another object). That method may also safely return the object to its invoker
我已經加粗的相關部分。您已經修改了從中接收對象的數組,因此它可能會消失。您可以在從陣列中刪除對象之前保留該對象,或者在完成對象後執行刪除操作。
其實,你可能是安全,即使在你的問題的代碼,因爲NSMutableArray中的實現的objectAtIndex的:可能做挽留隨後在退貨項目自動釋放。在多線程環境中,這將是唯一的方法來確保對象保持足夠長的時間以將其返回給調用者。但是,我沒有看到NSMutableArray的代碼,所以不要依賴它。
ETA:剛剛在看線程編程指南,看來NSMutableAtrray不會保留,autorelease。
爲了使結果清楚:NSArray和NSMutableArray類有一些例外,這些通用規則是從名稱不包含「new」,「copy」或「alloc」返回自動釋放對象的方法返回的對象,這意味着代碼在原來的問題是不安全的 – harms 2010-05-24 00:19:18
@harms不是這個規則只適用於對象創建? – sylvanaar 2010-05-24 00:35:05
@harms:沒有通用規則,從名稱不包含「new」,「copy」或「alloc」的方法返回的對象返回自動釋放對象。唯一的規則是您不擁有這樣的對象。 – JeremyP 2010-05-24 09:25:06