Tuesday, April 19, 2011

Beware of the self keyword within setter functions

If you have read my previous post Self keyword and setter functions, you will find it easier to follow along with this post.

In the last post, I asked you to use the self.member syntax when setting a member variable.

In this post, I am going to ask you not to use the self.member syntax within your setter function.

This is applicable only if you are writing your own custom setter function. The following example summarizes it all:

- (void)setMyArray:(NSArray*)tmpArray{

  // First, retain the value
  [tmpArray retain];

  // Next, release the previous value
  [myArray release];


  // Now here is where you need to be careful
  // Set the value
 
// WRONG: Don't use self.member within a setter function 
  // self.myArray = tmpArray


  // RIGHT: Always call the member variable directly within the   setter function
   myArray = tmpArray
}


Now for those of you who are still curious and wondering why you shouldn't use the self.member syntax within the setter function, here is the reason.

Using self.member syntax invokes the setter function of that variable, so if you use the self.member syntax within the setter function the setter function will be called recursively and your program will be in an infinite loop.

No comments:

Post a Comment