0

I define a property for a class in its implementation file.

@property (nonatomic, strong) IBOutlet UIView *headerView;

Then I override its getter function by -(UIView*)headerView(){...} to obtain some resources from main bundle.

In following code I need to set the property 'headerView' as subview to other views after it loads resource. Here are code fails to load resource.

[self.tableView setTableHeaderView:_headerView];

Getter function is not invoked. I change property variable to self.headerView:

[self.tableView setTableHeaderView:self.headerView];

It works now...

is there any difference between self.xxx and _xxx ? I think them identical to a property as different facets.

Alan Hoo
  • 445
  • 3
  • 12
  • 1
    [Difference between _ and self. in Objective-C](http://stackoverflow.com/questions/10333495/difference-between-and-self-in-objective-c) – Mário Cosme Jan 26 '16 at 15:20
  • Possible duplicate of [Difference between \_property and self.property](http://stackoverflow.com/questions/10889216/difference-between-property-and-self-property) – PaulDaPigeon Jan 26 '16 at 15:24

1 Answers1

5

Properties are backed by instance variables in Objective-C. Essentially, @property generates a getter and setter method by default that you access via self.property. If you use _property, you're bypassing the setter and getters and jumping straight to the instance variable. The only time you should use instance variables directly consist of in the init/dealloc or when you need to bypass a side effect someone may have implemented in a getter/setter method. Otherwise you should always use self.property rather _property to access and set your variables.

TheCodingArt
  • 3,436
  • 4
  • 30
  • 53