Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do people always use reassignment for instance variables in Objective-C (namely iPhone)?

I always see example code where in the viewDidLoad method, instead of saying, for example

someInstanceVar = [[Classname alloc] init];

they always go

Classname *tempVar = [[Classname alloc] init];
someInstanceVar = tempVar;
[tempVar release];

Why is this? Isn't it the exact same thing, just longer?

like image 753
Marty Avatar asked Sep 27 '10 18:09

Marty


1 Answers

The short answer: This pattern shows up all the time in iPhone code because it is considered the best way to create a new object and assign it to a member variable while still respecting all of the memory management rules and invoking the appropriate side effects (if any) while also avoiding the use of autorelease.

Details:

Your second example would create a zombie, since var is left holding a pointer to memory that has been released. A more likely usage case looks like this:

tempVar = [[Classname alloc] init];
self.propertyVar = tempVar;
[tempVar release];

Assuming that propertyVar is a declared as copy or retain property, this code hands off ownership of the new object to the class.

Update 1: The following code is equivalent, but not recommended* on iOS, which is probably why most iPhone programs use the first pattern instead.

self.propertyVar = [[[Classname alloc] init] autorelease];

* autorelease is discouraged on iOS because it can cause problems when overused. The easiest way to be sure you never overuse it is to never use it all, so you will quite often see iOS code that uses alloc/init and release, even when autorelease would be acceptable. This is a matter of coder preference.

Update 2: This pattern looks confusing at first because of the memory management that Cocoa performs automagically behind the scenes. The key to it all is the dot notation used to set the member variable. To help illustrate, consider that the following two lines of code are identical:

self.propertyVar = value;
[self setPropertyVar:value];

When you use the dot notation, Cocoa will invoke the property accessor for the indicated member variable. If that property has been defined as a copy or retain property (and that is the only way for this pattern to work without creating a zombie), then several very important things happen:

  1. Whatever value was previously stored in propertyVar is released
  2. The new value is retained or copied
  3. Any side effects (KVC/KVO notifications, for example) are automatically handled
like image 146
e.James Avatar answered Oct 17 '22 15:10

e.James