0

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?

Etan
  • 17,014
  • 17
  • 89
  • 148
  • 1
    By the way, never user assert() in production code. At the very least, use NSAssert, which will compile down to an assert in debug and will get wiped out in release. – Jack Lawrence Jun 05 '12 at 16:16
  • http://www.manicwave.com/blog/2009/10/30/defensive-programming-and-the-role-of-assertions/ – Etan Jun 05 '12 at 16:23
  • http://vgable.com/blog/2008/12/04/nsassert-considered-harmful/ – Etan Jun 05 '12 at 16:23
  • Whatever is causing your failure isn't in the code you posted. I copied and pasted it into a class along with a basically empty definition of X and see no error. (i.e. 'x' is visible and correct.) – Phillip Mills Jun 05 '12 at 16:25
  • @Etan thanks, I didn't know that. Guess I've got some code to change :) – Jack Lawrence Jun 05 '12 at 16:31

1 Answers1

3

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.

Gobra
  • 4,263
  • 2
  • 15
  • 20