Peter Warbo
Peter Warbo

Reputation: 11728

Objective-C - Correct init method

I have subclassed UITableViewCell and in the - (id)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier I'm setting some instance variables like so:

_image = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"image.png"]]

I'm not using any accessor because Apple recommends not using accessors in init and dealloc.

So far so good. My question is after I've set the _image I want to set userInteractionEnabled to YES for the image. Should I do it with the getter or should I use the ivar directly?

self.image.userInteractionEnabled = YES;

Or

_image.userInteractionEnabled = YES;

Which style is preferred of using?

Upvotes: 1

Views: 119

Answers (3)

Peter Hosey
Peter Hosey

Reputation: 96373

A third option: Assign the image to a local variable, set it up completely (e.g., its userInteractionEnabled) using that, and then assign it to the instance variable from the local variable.

Upvotes: 1

Eiko
Eiko

Reputation: 25632

The recommendation still holds: use the ivar directly in init. If you ever implement a custom accessor on that property (now or later, here or when subclassing), you might be in trouble.

Upvotes: 4

Trausti Thor
Trausti Thor

Reputation: 3774

Since this is a property value, self.image... is more correct, it will make sure all notifications are sent and if anything else is observing the object is run. If you use _image... none of the notifications are sent.

Upvotes: -1

Related Questions