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?

5
  • 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. Commented Jun 5, 2012 at 16:16
  • manicwave.com/blog/2009/10/30/… Commented Jun 5, 2012 at 16:23
  • vgable.com/blog/2008/12/04/nsassert-considered-harmful Commented Jun 5, 2012 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.) Commented Jun 5, 2012 at 16:25
  • @Etan thanks, I didn't know that. Guess I've got some code to change :) Commented Jun 5, 2012 at 16:31

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.