Search code examples
objective-cxcodeself

What is the main use of self?


I am working on a ARC based project. I am just wondering what is the main use of self ?

I am having an array as follows

@property(strong,nonatomic)NSMutable *dataArray;

I am initializing the array as follows

-(void)viewDidLoad{

 self.dataArray=[[NSMutableArray alloc]initWithObjects:@"one",@"two",nil];  //first method

}

or

-(void)viewDidLoad{

 dataArray=[[NSMutableArray alloc]initWithObjects:@"one",@"two",nil];  //second method

}

Can anyone tell me what is the difference between my first and second method ?


Solution

  • After lot googling I found the answer to my question ,

    @property (nonatomic, retain) NSDate *timestamp;

    Objective C will generate the getter and setter as follows

    (NSDate *)timestamp
    {
       return timestamp;
    }
    
    (void)setTimestamp:(NSDate *)newValue
    {
       if (timestamp != newValue)
       {
          [timestamp release];
    
          timestamp = [newValue retain];
       }
    }
    

    The setter method can be invoked only as follows

    self.timestamp = [NSDate date];

    where as

    timestamp=[NSDate date];

    does not invoke the setter method.

    Without the self object and the dot we are no longer sending an object a message but

    directly accessing the ivar named timestamp.

    Conclusion: When we don't use self , the old value won't be released ,because the setter

    method won't be invoked i.e Prior to ARC.But in ARC I am not pretty sure about this.As far

    as I heard , With ARC either way of setting the ivar is correct as far as memory management

    is concerned.