Memory Management Part 1
Developing applications requires memory management. In this case, Apple provides a garbage collector for the Mac applications but not for the iPhone. From my point of my I found no reason at all, to avoid using the garbage collector and I would love to know if you think otherwise.
So let’s start: Retain count – Retain – Release
So every object has a retain count. This is an integer property of each object. For example
myObject *p = [[myObject alloc] init]; // count is now set to 1. [p retain]; // count is now set to 2. [p release]; // count is now set to 1. [p release]; // count is now set to 0.
The moment you allocate an object the retain count becomes 1. If you would like to share this object to other objects you will need to retain the object. The retain method will increase the counter by 1. In case you want to decrease the count you can do it using the release method.
Note: If the count is 0 then the object is freed.
Ownership
You own an object when you alloc it, copy it or new it. If you own an object you need to release it. Consider an NSString
NSString *example = [[NSString alloc] initWithString:@"someText"]; // use the above string in your code [example release]; // once you finish using it, you need to release it.
If you do not own an object then you are not responsible for releasing it unless you have explicitly retained it. Consider an NSString stringWithString
NSString *example = [NSString stringWithString:@"someText"];
Which is equal to:
NSString *example = [[[NSString alloc] initWithString:@"someText"] autorelease];
Autorelease
What if you want to have a method that returns an NSString?
-(NSString*)returnString{ NSString *stringToReturn = [[NSString alloc] initWithString:@"hello"]; // if you release it the string will be deallocated // and the application will crash. // If you don't release it then you will have a leak. return stringToReturn; }
So what can we do? We can call the autorelease method which simply indicates that the object will be released in the future.
-(NSString*)returnString{ NSString *stringToReturn = [[NSString alloc] initWithString:@"hello"]; [stringToReturn autorelease]; return stringToReturn; }
Autorelease Pool
Every time you call the autorelease method from an object, is added to the outer-most autorelease pool. When the pool is release or drained, it simply sends release to all the objects in the pool. More precisely:
// create your own little autorelease pool NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init]; // these objects get added to the autorelease pool you created above NSString *string1 = [self returnString]; NSString *string2 = [self returnString]; // use the above strings ... ... // they will be released when the pool is released [pool release]; // all objects added to this pool are released
This concludes todays post
More will come regarding the properties in Objective-C.