#memory management

10 posts with this tag

Double retaining with a retained property

October 19, 2011

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 al…

Passing with `&`

October 04, 2011

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), you simply al…

Clearing the delegate when dealloc-ing

September 25, 2011

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…

Custom setter and getters

March 25, 2011

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…