Saturday, November 22, 2008

Objective C forward declaration

Was 'debugging' this for few hours, nothing more than not reading the documentations carefully. I needed to create a forward declaration of a class A in my class B as I would need to access some properties in class A.

However when compiling XCode was complaining to me about 'error: request for member in something not a structure or union'. Cracked my brain, tried rewriting my accessors in class A. Checking the access rights, property declarations, all was in order.

Finally did the google ritual and found out that to access properties in a forward declared class you must include the interface file in the implementation file of the class accessing. Too abstract to talk about here's the example:

Class B .h file

#import ....

//forward declare class a
@class A

@interface B

Class B .m file

//import interface file for class A
#import "classA.h"

@implementation B
A.someProperty = @"Got me there";

Hope this helps.. :)


Xcode cowboy said...

Hi Toh,

I was getting the same error and your suggestion solved the problem. However, I didn't declare "@myclass" in the header file. Only the .m import statement. What difference does the "@myclass" declaration make?

Toh Yen Cheng said...

hi xcode cowboy,

sorry for the late reply. for the header file it's for forward declaration. you do not have any myclass properties in the interface file hence you would not need it. but if you had declared a property in the interface file then you'll need to forward declare the class.

best regards.