Subclass of class with synthesized readonly property cannot access instance variable in Objective-C

tacos_tacos_tacos picture tacos_tacos_tacos · Jun 8, 2012 · Viewed 10.7k times · Source

In the superclass MyClass:

@interface MyClass : NSObject

@property (nonatomic, strong, readonly) NSString *pString;

@end

@implementation MyClass

@synthesize pString = _pString;

@end

In the subclass MySubclass

@interface MySubclass : MyClass

@end

@implementation MySubclass

- (id)init {
    if (self = [super init]) {
        _pString = @"Some string";
    }
    return self;
}

The problem is that the compiler doesn't think that _pString is a member of MySubclass, but I have no problem accessing it in MyClass.

What am I missing?

Answer

Sergey Kalinichenko picture Sergey Kalinichenko · Jun 8, 2012

The instance variable _pString produced by @synthesize is private to MyClass. You need to make it protected in order for MySubclass to be able to access it.

Add an ivar declaration for _pString in the @protected section of MyClass, like this:

@interface MyClass : NSObject {
    @protected
    NSString *_pString;
}

@property (nonatomic, strong, readonly) NSString *pString;

@end

Now synthesize the accessors as usual, and your variable will become accessible to your subclass.