If you have ever seen the following pattern and wondered why: NSObject *newObject = [[object retain] autorelease]; return newObject; Well wonder no more! The reason behind this retain/autorelease pattern is to ensure that the "object" will not be destroyed until the caller's autorelease pool drains so protecting the caller from other threads releasing the "object" in the middle of an access.…
#memory management
10 posts with this tag
A common mistake I see over and over again in code is the accidental double retain. This happens when an object is set to a property that has the attribute retain which results in a memory leak. Let's look at an example of this happening: @property (retain) UIView *doubleRetainedView; @property (retain) UIView *singleRetainedView; - (void) doubleRetainMethod { self.doubleRetainedView = [[UIView alloc] init]; } - (void) singleRetainMethodA { self.singleRetainedView = [[[UIView alloc] init] auto…
The only time you should call [self release] is if during the initialization of your object an error occurs that causes you to return nil. - (id) initWithData:(NSData *)userData error:(NSError **)error { if(!userData){ if(error){ *error = //set up error } [self release]; return nil; } //more code } This is because if we just return nil, we will have alloc'd memory but never be able to release it so…
In Objective-C you pass by reference by placing the "&" symbol (minus the quote marks) in-front of the variable name i.e. &var instead of just var . This informs the compiler to pass the memory address of the variable rather than its value. This is useful when you want to update that variable value but the method may also produce an error, rather than "overloading" the return value to handle both a successful and unsuccessful execution (an any casting issues that may then crop up…
Often when creating a delegate relationship between two objects: A (delegate) and B (delegating object), you can sometimes run into the scenario where the delegating object outlives the delegate. Meaning that if we don't inform B that A is dealloc'ed we could end up with a fatal app crash. To flesh this idea out consider the below (contrived) example: //some code here inside A self.b = [[[B alloc] init] autorelease]; self.b.delegate = self; //some code here Now C comes along retains B (some time passes) an…
In Objective-C, a property can have the following attributes applied to it: atomic nonatomic assign retain copy The scenerio is that these attributes are applied to the properties for us but what happens if we want setting/getting a property's value to have a side-effect? In this article, I implement the different possible combinations of property attributes to show how we can have custom getters and setters in our .m files while still honouring the property attributes declared in our .h files. Non-atomi…