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 autore…
#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; @pro…
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 err…
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 th…
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. T…
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 th…
Objective-C automatically passes two hidden method arguments with ever method call: * self - the object that the method is executing inside * _cmd - method's message call Here's an example of using _cmd: NSLog(@"%@", NSStringFromSelector(_cmd));…
A colleague recently came to me with a bug in his code, that he just couldn’t solve. He was attempting to call a static/class method from inside an instance method of his class using self, assuming that as self was an instance of the class it would have access to all the methods defined in that clas…
When using the debugger within Xcode, you see that each object has a isa variable. For those, like me, curious about what is does. When you use alloc on a class, you are actually creating space in memory which is temporary filled, at the bottom of this space you point to another memory address. Th…