Madbreaks
Madbreaks

Reputation: 19539

Objective C - Can't set superclass property in subclass

Take this simple class hierarchy:

Tree.h:

@interface Tree : NSObject
@property (nonatomic, assign) id<TreeDelegate> delegate;
@end

Tree.m:

@implementation Tree
@synthesize delegate;
@end

Aspen.h:

@interface Aspen : Tree
- (void)grow:(id<TreeDelegate>)delegate;
@end

Aspen.m:

@implementation Aspen
- (void) grow:(id<TreeDelegate>)d {
    self.delegate = d;
}
@end

When I try to do self.delegate = d;, I'm getting the following error:

-[Aspen setDelegate:]: unrecognized selector sent to instance 0x586da00

I was expecting the Tree parent class's delegate property to be visible to the subclass as-is, but it doesn't seem to be since the error indicates the parent class's synthesized setter isn't visible.

What am I missing? Do I have to redeclare the property at the subclass level? I tried adding @dynamic at the top of the implementation of Aspen but that didn't work either. Such a simple concept here, but I've lost an hour searching around trying to find a solution. Out of ideas at this point.

--EDIT--

The above code is just a very stripped-down example to demonstrate the issue I'm seeing.

Upvotes: 0

Views: 1706

Answers (2)

Madbreaks
Madbreaks

Reputation: 19539

I was finally able to figure this out. My actual code leverages a 3rd party static library that defines the classes Tree and Aspen in my example. I had built a new version of the static library that exposed the Tree delegate given in my example, however I did not properly re-link the library after adding it to my project and as a result the old version was still being accessed at runtime.

Lessons learned: be diligent with steps to import a 3rd party library, and when simple fundamental programming concepts (such as in my example text) aren't working, take a step back and make sure you've dotted i's and crossed t's.

Upvotes: 0

Mecki
Mecki

Reputation: 132879

I just tried your code, supplemented by the protocol, an object implementing it, the necessary import and a main function and on my system it works like a charm:

#import <Foundation/Foundation.h>

@protocol TreeDelegate <NSObject>
@end

@interface MyDelegate : NSObject <TreeDelegate>
@end

@implementation MyDelegate
@end

@interface Tree : NSObject
@property (nonatomic, assign) id<TreeDelegate> delegate;
@end

@interface Aspen : Tree
- (void)grow:(id<TreeDelegate>)delegate;
@end

@implementation Tree
@synthesize delegate;
@end

@implementation Aspen
- (void) grow:(id<TreeDelegate>)d {
    self.delegate = d;
}
@end

int main(int argc, char ** argv) {
    MyDelegate * d = [[MyDelegate alloc] init];
    Aspen * a = [[Aspen alloc] init];

    [a grow:d];
    return 0;
}

Upvotes: 1

Related Questions