Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does a subclass @property with no corresponding ivar hide superclass ivars?

The following seems simple enough. There's a superclass with an ivar, and a subclass which accesses the (@protected) superclasses ivar:

// Testclass.h    
@interface TestClass : NSObject {
    NSString *testIvar;
}
@end

//TestClass.m
@implementation TestClass
@end

//TestSubclass.h
@interface TestSubClass : TestClass {
}

@property (nonatomic, retain) NSString *testProperty;
- (void) testMethod;

@end

//TestSubclass.m    
#import "TestSubClass.h"
@implementation TestSubClass

@synthesize testProperty;

- (void) testMethod{
    NSLog(@"The value was: %@", testIvar);
}
@end

Simple and correct-seeming enough. However, attempting to compile (for iOS 4.2 SDK, with GCC 4.2) produces this error pointing to the NSLog line: 'testIvar undeclared'.

I'm new to Objective-C, but can't for the life of me see why this should be an error. Comment out the testProperty stuff, and it compiles OK. It seems like adding a synthesized property in a subclass, without a corresponding ivar, is actually hiding an unrelated superclass ivar.

Can anyone enlighten me as to what's happening here? Relatedly, was the compilation error foreseeable? (Foreseeing it would have saved me some time and frustration).

like image 663
Cris Avatar asked Oct 18 '10 07:10

Cris


2 Answers

LLVM compiles the source without complaints, switch to LLVM: Select target → Get Info → Build → C/C++ Compiler Version → LLVM 1.5. From my limited experience it’s a better compiler anyway. No idea why GCC behaves the way it does – interesting catch.

like image 89
zoul Avatar answered Nov 15 '22 23:11

zoul


The testIvar undeclared error is actually red herring in this case. This message seems to be caused by testProperty not having a corresponding ivar. To resolve the issue either declare a testProperty ivar in TestSubClass.h or make testProperty @dynamic in TestSubClass.m.

like image 41
bspenla Avatar answered Nov 15 '22 22:11

bspenla