Question

I have a question regarding variable scope with subclasses.

I have something like the following:

ParentClass.h

@interface ParentClass : NSObject

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

- (id)initWithIdentifier:(NSString *)identifier;

@end

ParentClass.m

@interface ParentClass() 
@property (nonatomic, strong) NSString *myIdentifier;
@end

@implementation ParentClass 

- (id)initWithIdentifier:(NSString *)identifier {
    if (self = [super init]) {
       self.myIdentifier = identifier;
    }
    return self;
}
@end

ChildClass.h

@interface ChildClass : ParentClass

- (NSString *)showMeTheIdentifier;

@end

ChildClass.m

@implementation ChildClass

- (NSString *)showMeTheIdentifier {
    return self.myIdentifier;
}

Then I go to implement the class and I get no compiler warnings, but the result of the NSLog is (null)

ViewController.m

...
ChildClass *c = [[ChildClass alloc] initWithIdentifier:@"abc123"];
NSLog(@"What's my identifier? %@", [c showMeTheIdentifier]);
...

What am I doing wrong?

Thanks

Was it helpful?

Solution

Aside from the fact that you have self == [super init] instead of self = [super init] in your "pseudo code" (you're comparing self to [super init] instead of assigning it), everything looks fine. If you're are using == in your actual code, self is returning nil. You may want to try logging the actual child class and see if the object exists after you instantiate it (or set a break point and check the debugger). That'll tell you if the problem is in instantiation or elsewhere.

Most likely, there's some other detail in your actual code that's causing the problem. It's possible that something you think isn't related is actually the problem. I've done this before when posting questions. I try to cut out the "cruft" and end up also cutting out the problem. You may want to try posting your actual code.

OTHER TIPS

You can remove the property declaration in the private category and do something like this:

You are not returning self in init. Hence it does not work.

- (id)initWithIdentifier:(NSString *)identifier {
    self = [super init];
    if(self) {
        _myIdentifier = identifier;
    }
    return self;
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top