-1

Possible Duplicate:
Objective-C - When to use 'self'

I needed a variable to be passed from one view to another so I made a property called StringC in the .h and accessed it using self.StringC (that part worked).

I also need some arrays that are accessible throughout the view but I'm using them differently.

For instance I have lvLabelArray and I'm using

self.lvLabelArray=[[NSMutableArray alloc]init];

and then later I'm using

[lvLabelArray addObject:LabelText];

Is there a difference between that and

[self.lvLabelArray addObject:LabelText];

?

Sorry I don't know the terms for those kinds of variables.

Community
  • 1
  • 1
user1515993
  • 69
  • 1
  • 7

1 Answers1

1

There is an important difference there.

self.attribute goes through the object's getter or setter function, as appropriate. That allows you to set up initial values, trigger update messages, or anything else.

Accessing "attribute" directly goes straight to the underlying variable, so you bypass all that. As a result, it's definitely the less-preferable way of working.

A common way of avoiding this confusion, and just plain mistakes, is to rename the underlying variable. Instead of just "@synthesize attribute", use "@synthesize attribute = _attribute". This will create the getter and setter methods as before, but they'll the underlying variable is named "_attribute". That means that trying to use "attribute" without "self" will trigger a compiler error.

Patrick
  • 56
  • 2