开发者

Objective-C memory management: if I alloc init multiple times, do I need to release multiple times?

开发者 https://www.devze.com 2023-01-07 23:10 出处:网络
开发者_JAVA技巧If I have a UIPopoverController (in .h file) and alloc init it multiple times in the same .m file. do I need to release it once to multiple times?Reference count is at stake here.
开发者_JAVA技巧

If I have a UIPopoverController (in .h file) and alloc init it multiple times in the same .m file. do I need to release it once to multiple times?


Reference count is at stake here.

Here's the rule: objects die when no one owns them anymore. If you lose the reference to it without releasing it, you leak.

There are two common ways to gain ownership over an object:

  • You create it yourself (by calling the alloc method)
  • You call retain on it

And, as well, there are two common ways to relinquish ownership over an object:

  • You call release on it
  • You call autorelease on it

So each time you allocate an object, you are responsible for releasing it once you're done with it. This probably means you only have to release it once, even though you can create it through several code paths. However, you must ensure you release it if you're going to overwrite the variable with a new object.


You don't alloc an object multiple times. You create it by allocing it once. Each time you send alloc to a class, you create another new instance. Since you alloced all these instances, (see the memory management rules), you must release or autorelease them all.

0

精彩评论

暂无评论...
验证码 换一张
取 消