Are there any rules of thumb when working with Objective-C that would help me understand when is the right time to release variables?
相关问题
- CALayer - backgroundColor flipped?
- What uses more memory in c++? An 2 ints or 2 funct
- Core Data lightweight migration crashes after App
- back button text does not change
- Achieving the equivalent of a variable-length (loc
相关文章
- 现在使用swift开发ios应用好还是swift?
- TCC __TCCAccessRequest_block_invoke
- xcode 4 garbage collection removed?
- Xcode: Is there a way to change line spacing (UI L
- Unable to process app at this time due to a genera
- How can I add media attachments to my push notific
- didBeginContact:(SKPhysicsContact *)contact not in
- Custom Marker performance iOS, crash with result “
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
oralloc
, 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, yourelease
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'tnew
,alloc
,retain
orcopy
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).NARC! :)
If you invoked a method that contains N ew, A lloc, R etain, or C opy, then you must
release
orautorelease
. 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.
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.
There’s a nice tutorial by Scott Stevenson called Learn Objective-C. It also contains a section about memory management.