iOS Dev Nugget 4 Prefer accessors to accessing private variables directly


Need to run a code review on your codebase? Hire me

Use accessors everywhere, as much as possible.

Use them in -init and -initWithFrame:. If you provide an implementation for your own setter function, you'll need to synthesize it so you can access the private variable directly. The @synthesize statement also helps as a documentation cue to indicate you are accessing the private variable somewhere.

Define a property like:

@property (nonatomic,strong) NSString username;

and use self.username everywhere, except in the -(void)setUsername: function. And if you implement -setUsername: you'll also need to do a:

@synthesize username;

This makes it easy to control access to data, implementing caching and lazy initialization, as well as trigger related updates or process. I implement setters often in UIViewController subclasses to kick start a network fetch request for the data to be displayed in a view controller. For example, -setUsername: with a non empty string can begin fetching a user's profile.

Your feedback is valuable: Do you want more nuggets like this?   Yes   or   No


Like this and want such iOS dev nuggets to be emailed to you, weekly?

Sign Me Up! or follow @iosdevnuggets on Twitter


View archives of past issues