سؤال

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.

هل كانت مفيدة؟

المحلول

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.")

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top