Search code examples
iosobjective-cpropertiesprotocolsinstance-variables

Access instance variables of properties inherited from protocols


I have created a simple protocol which enforces an NSString property on conforming classes:

@protocol CPTSettingViewModel <NSObject>

@property (nonatomic) NSString *titleText;

@end

When I create a class which conforms to this protocol, Xcode suggests that I synthsize the property:

@synthesize titleText;

My issue is that when I then try to reference this property's instance variable in my initialiser, I receive the error:

Use of undeclared identifier '_titleText'; did you mean 'titleText'?

How can I access instance variables of properties inherited from protocols rather than ending up with something like this where I use the property itself?

- (instancetype)initWithTitleText:(NSString *)titleText selectionText:(NSString *)selectionText {
    self = [super init];
    if (self) {
        self.titleText = titleText;
        _selectionText = selectionText;
    }
    return self;
}

Solution

  • The default instance variable name when you use @synthesize is the name of the property itself -- titleText in this case. The default auto-synthesis (which does not work due to the property being in the protocol) will insert the equivalent to @synthesize titleText = _titleText, which is how the underscores become the usual name in that case. I believe you can just specify the name with the underscore (i.e. @synthesize titleText = _titleText) to have the instance variable name then match what you are expecting.