Search code examples
objective-cinheritancescopeinstance-variablesprotected

Understanding inheritance of Objective-C instance variables


I would like to extend a method of a superclass A with new functionality by subclassing it in B. Since instance variables default to @protected, accessing them should be fine. However, changes to an instance variable x that I make in the method of A are not reflected to B and vice versa.

@interface A : NSObject {
    X *x;
}

- initWithX:(X *)anX;

@end

@implementation A

- initWithX:(X *)anX
{
    assert(anX != nil);
    if (self = [super init]) {
        x = anX;
    }
    assert(self != nil);
    return self;
}

@end

@interface B : A

@end

@implementation B

- initWithX:(X *)anX
{
    assert(anX != nil);
    if (self = [super initWithX:anX]) {
        assert(x != nil);      <<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<<< FAILS
    }
    return self;
}

@end

How can I share the variable x between A and B?


Solution

  • Check your code yet again. And even yet again. This code must be working, really... It's a kind of basic relationship between inherited and parent interface and it should operate just like you expect.

    It must be something in the code you've stripped from the sample.