What are the iPhone OS memory management rules and how do you know?

I am currently jumping into ice-cold water called “Memory Management on iPhone OS”.

Here is one rule that I learned:

Each time I see alloc in my method, I will output the corresponding variable at the bottom of the method.

Each time I create @property (...) in my header file that says to copy or save, I put a release message about this variable in the dealloc method.

Every time I have an IBOutlet, I do the same. Only exception: if IBOutlet has something like @property (... assign) or in other words: if it has the assign keyword. Then I do not want to release it in the dealloc method.

I feel that there are many more good rules! Just write what you have. May he clean them all together. Links to great descriptions are also welcome.

+5
source share
4 answers

Actually, every time you initialize an object, and the method name includes "init", you are responsible for freeing it. If you create an object using a class method that does not include the word "init", then you do not.

For example:

  NSString *person = [NSString stringWithFormat:"My name is %@", name];

no release required. But:

  Person *person = [[Person alloc] init];

release required (as you said in your question). Similar:

  Person *person = [[Person alloc] initWithName:@"Matt"]];

release is also required.

This is an agreement, not a language rule, but you will find that it is true for all APIs supplied by Apple.

+4

, segfaults spring , , . , , Apple, .

+2

, , . :

  • -, .
  • , , .
  • , NSAutoreleasePool, , (, ).

, . , , , .

For object properties, and not for deleting them in my dealloc method, I like to assign nil to them. Thus, saved or copied properties are sent by the release, and the assigned properties are simply overwritten, and I do not need to update my dealloc method if I change the property to / from the saved one.

+1
source

All Articles