Ser Pounce
Ser Pounce

Reputation: 14571

Problems referencing iVar in inner class

I have a class called MyClass which has a small nested inner class called MyInnerClass. The implementation file looks like the following (and also contains an ivar of the nested inner class) :

@class MyInnerClass;

@interface MyClass
{
MyInnerClass *myInnerClassIvar;
}
@property(nonatomic, retain) MyInnerClass *myInnerClassIvar;

@end

Then in the implementation file, I implement both MyClass and MyInnerClass. Looks like the following:

@interface MyInnerClass
{
iVar *x;
}

@property(nonatomic, retain) iVar *x;
@end

@implementation MyInnerClass
@synthesize x;
...
@end

@implementation MyClass
@synthesize myInnerClassIvar;
...
@end

I am now creating a subclass for MyClass, and in it I'm trying to make a call like this:

self.myInnerClassIvar.x

And I'm getting the following message:

Property x cannot be found in in forward class object MyInnerClass *

Am I forgetting something? Haven't implemented an inner class before, see no reason why this shouldn't work.

UPDATED: I moved the interface of MyInnerClass to the .h of MyClass and everything works. Is this a good solution?

Upvotes: 2

Views: 520

Answers (2)

Ser Pounce
Ser Pounce

Reputation: 14571

I moved the interface of MyInnerClass into the .h file of MyClass like following:

MyClass.h

@class MyInnerClass;

@interface MyClass
{
MyInnerClass *myInnerClassIvar;
}
@property(nonatomic, retain) MyInnerClass *myInnerClassIvar;

@end

@interface MyInnerClass
{
iVar *x;
}

@property(nonatomic, retain) iVar *x;
@end

I'll wait before I check this off as the answer because based on the previous answer, I know there is some skepticism. The only reason I tried this is because I saw it in the Apple example SimpleTextInput, except in that one the entire inner class is in the .m file. Anyway, would be interested to hear what people have to say about this, if it might incur unwanted side effects later or if its ok.

Upvotes: 0

Damo
Damo

Reputation: 12900

I believe that Objective-C does not have inner classes in the sense that you are trying to implement. See SO. But regarding your question...

in MyClass.h there is no mention of the iVars of MyInnerClass - it is a forward definition, i.e. @class MyInnerClass therefore MySubClass has no reference point for x.

If you define two classes MyClass & MyInnerClass (probably a bad thing to name it that considering...) - have them in two separate .h files and two separate .m files (ie. as normal). Make an @property in MyClass of type MyInnerClass. Then in MySubClass you need to import both MyClass & MyInnerClass.

Upvotes: 2

Related Questions