2/22/2011

Memory Management Issues in xCode

I will update this post whenever I learn a new memory management method or encounter memory management related problem.

Retain versus Copy: Retain doesn't create a new object, so it increases the retain count of the retained object. (And because the new object is exactly the same object as the old object they have the same retain count). Copy creates a new object, so it increases the retain count of the new object.


Release versus Autorelease:
Both of them are used to release allocated or copied variables. In other words, it decreases retain count of objects.
Sending release to an object immediately decreases retain count.
Sending autorelease instead of release to an object extends the lifetime of that object at least until the pool itself is released. The pool must be released within the same context.

If you write a loop that creates many temporary objects, you may create an autorelease pool inside the loop to dispose of those objects before the next iteration. This can help reduce the maximum memory footprint of the application.

Convenience Constructor: This constructor deals with the initialization of objects but when it is used, the ownership of allocation objects becomes the object itself. You cannot release any instance that is allocated by constructor directly. You can only release your owned instances. autorelease is used in this constructor.

Collection handling: Collections auto retain objects whenever they are added.
[array addObject:convenienceNumber] --- Object is retained. If you allocated the object instead of using constructor, you must release it if you don't want to use it after.

Example of collection handling:
NSMutableArray *array;
NSUInteger i;
for (i = 0; i <>
NSNumber *allocedNumber = [[NSNumber alloc] initWithInteger: i];
[array addObject:allocedNumber];
[allocedNumber release];
}

Getter and Setter Methods:
- (NSString*) title {
return title;
}
- (void) setTitle: (NSString*) newTitle {
[title autorelease];
title = [newTitle retain];
}

Accessors Methods: This methods are used for encapsulation of memory management in programming.
@property (nonatomic, retain) - atomic as default. specify the way the object will transfer the data when performing a set operation

@synthesize - synthesize proper setter and getter for the object. You may use built-in classes for synthesizing.









No comments:

Post a Comment