0

I recently read a post about no longer needing to declare ivars as well as properties on ViewControllers, and have been removing the duplicate declarations from my code as I notice them.

A really puzzling effect I've noticed is that if the property lacks a declared ivar, it needs to be preceded by self. Eg:

CustomVC.h:

@interface CustomVC : UIViewController <UITableViewDelegate,UITableViewDataSource> {
...
@property (nonatomic, strong) IBOutlet UITableView *itemsTableView;

CustomVC.m:

[itemsTableView reloadData]; // cellForRowAtIndexPath not called
[self.itemsTableView reloadData]; // table view refreshed as expected

If there was a problem with accessing the variable without self., I'd expect a compile time or runtime error, but it seems to just silently fail, making it vary difficult to debug.

Echilon
  • 10,064
  • 33
  • 131
  • 217

1 Answers1

1

it's not the same to call the ivar (direct access) and using self.myIvar (which is an accessor method - properties- ).

When you're using direct ivar access it doesn't notify observers and thus doesn't trigger some events. It's always best to use self.myIvar (some won't agree though).

read the answer in the link which is very detailed and very interesting.

another good point is to synthesize properties like this :

@synthesize myIvar = myIvar_;

This will ensure you to avoid direct access to the ivar by mistake (forgetting the "self.")

Community
  • 1
  • 1
moxy
  • 1,634
  • 1
  • 11
  • 19
  • The behaviour I'm seeing is almost as if when omitting `self.`, the property simple isn't updated. – Echilon Mar 31 '12 at 13:07
  • Yes, **when omitting "self." you're accessing directly the ivar** and not using property (so observers won't be notified), when you're using "self." you are accessing the property and thus notifying observers that your value changed, etc. – moxy Mar 31 '12 at 13:25
  • I half understand. The odd thing is that if I have for example an array property, accessed without `self.`, I can add objects to it and when I do a count afterwards, it's still empty. – Echilon Mar 31 '12 at 14:08
  • NSArray *myArray = [[NSArray alloc] initWithObjects:@"bla",@"bli",@"blo",nil]; NSLog(@"%d",[myArray count]); you should get 3 in console. "self." is for accessing properties of a class, it reprensent the instance you will work with. about your array question, it's better to open another question with the chunks of code you're using and in which methods because your problem might come from variables scope too. – moxy Mar 31 '12 at 14:23