Monday, April 18, 2011

Self keyword and setter functions

Let me begin this post with an example:
Consider this variable:

NSArray * myArray;
@property(nonatomic, retain) NSArray * myArray;

The above lines of code causes the compiler to generate a default setter function for the myArray variable which retains the variable.

The compiler generated setter function would like something like:

(void)setMyArray:(NSArray *)tmpMyArray{
  [tmpMyArray retain];
  [myArray release];
  myArray = tmpMyArray;

Observe that the setter function releases the current myArray before assigning a new value to it. That is why, when we set a value to a variable we should always ensure that we use the self.member syntax.

// The following line invokes the setter function to set this value
self.myArray = anArray;

// The following line does not invoke the setter function and thus causes a memory leak because release is not called on the previous value of myArray.
myArray = anArray;

Another thing to be remembered is, if we are defining a custom setter function, we MUST implement all the steps that a compiler-generated setter would contain.

1 comment:

  1. Great article, it was very helpful! I just started in this and I'm getting to know it better! Cheers, keep up the good work!

    PIC Scheme Singapore