Is there a quick rule to know when to release Objective-C variables?

微笑、不失礼 提交于 2019-12-08 05:10:02

问题


Are there any rules of thumb when working with Objective-C that would help me understand when is the right time to release variables?


回答1:


NARC! :)

If you invoked a method that contains N ew, A lloc, R etain, or C opy, then you must release or autorelease. Otherwise you don't touch it.

Of course, anything the documentation explicitly says trumps this rule.

The other thing is that when you're dealing with C function the NARC rule still applies, but also gets the Create rule: if the function contains "create", then you're responsible for CFReleasing or freeing the returned data.




回答2:


I would highly recommend you read through the memory management rules a few times. It's pretty short and not difficult, and once you've understood what's in that document, you won't ever have to wonder.

Basically, think of it as ownership. When you create an object with new, copy or alloc, or when you retain an object, you own that object. An object will not go away as long as it has owners. When you're done with an object, you release it, thus giving up your ownership. When the object has no more owners, it can go away and might be deallocated. Any object that you didn't new, alloc, retain or copy is not owned by you and can't be guaranteed to stay around past the current call chain (i.e., it's OK to use it or return it but not to store it for later use).




回答3:


The resource utlisation thumb rule is "Acquire late and release early". This means you should acquire a resource as late as possible and release as early as possible. The lifespan of your usage should be as low as possible.




回答4:


There’s a nice tutorial by Scott Stevenson called Learn Objective-C. It also contains a section about memory management.



来源:https://stackoverflow.com/questions/3067120/is-there-a-quick-rule-to-know-when-to-release-objective-c-variables

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!