Release problems in Objective-C
I would like to ask about the memory management problems in objective C. I am the green of the objective C. When I read some of the sample program from the Apple website, I saw a [XXX release]. I guess this statement is used to release the use of the variable. However, when I use this statement in my program, I got some problems. I used the NSLog() to display the content, but it cannot display the content, it shows some statement about the release.
does t开发者_StackOverflowhe objective C has the auto memory management just like java? or we need to care about the memory problems by the program.
Thank you very much.
Objective-C does have garbage collection ("auto memory management"), but only on the Mac. It is not available on the iPhone. However, the rule of memory management is not that complicated. It is:
If you were given an object via a method (or function) that contains the word new
, alloc
, retain
, or copy
, then you must either release
the object or autorelease
it.
That's pretty much it. If you always follow this convention, then 99.999% of the time you're going to be OK. The other 0.001% of the time, read the documentation (or ask us here on StackOverflow! :) ).
(I'll also add that anything the documentation says that contradicts this rule wins.)
Read the Memory Management Rules. Just knowing those few simple rules will tell you all you need to know about memory management in Objective-C.
You only need to call release
on objects you init
/alloc
yourself or your instance variables in your class dealloc
method.
Objective-C does have auto release pools.
精彩评论