rihekopo
rihekopo

Reputation: 3350

Objective C - underscore needed without @synthesize?

I get an error from this method, i have an imageView property linked to the header file from my storyboard, but it works only when i use the _imageView instead of imageView. The original code uses the imageView version without underscore, but it has a @synthesize imageView line under the @implementation. Do i need the underscore because of the lack of @synthesize?

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSDictionary *filteredDictionary = [filterNames objectAtIndex:indexPath.row];
imageView.image = [filteredDictionary objectForKey:@"filteredImage"];

Upvotes: 0

Views: 125

Answers (3)

Vlad Papko
Vlad Papko

Reputation: 13302

There are two possible variants to access instance variable:

  1. By using property. In this case you should use self.imageView
  2. By direct access to the variable. Code for access depends on using @synthesize or not.
    If you don't use @synthesize then compiler automatically creates instance variable for you with underscore: _imageView.
    If you use @synthesize imageView or @synthesize imageView = imageView then you should access instance variable by calling: imageView without underscore.

Upvotes: 1

Douglas
Douglas

Reputation: 2524

In the current version of Xcode it does the @synthesize for you behind the scenes. But in doing so forces you to use the underscore. It is similar to you using @synthesize imageView = _imageView. So if you don't synthesize use the underscore.

Upvotes: 1

Tommy
Tommy

Reputation: 100632

Yes, Apple flip flopped on this.

If you add the default @synthesize::

@synthesize propertyName;

Then the instance variable will be called propertyName. If you omit the @synthesize and allow it to be inferred implicitly, the instance variable will be called _propertyName.

I guess one internal school of thought ended up winning over another.

Upvotes: 2

Related Questions