Slayter
Slayter

Reputation: 1170

Objective-C - pass reference of self to child object

I'm working on an Objective-C where I need to pass a reference of self to a child object. For instance in Java if I was to do this within a method I could say room.place(this); How can I do something like this in Objective-C. I know I can pass self as a method parameter but the child object needs to #import the other class and when they both import each other then I start to get errors. Any help would be appreciated.

Upvotes: 0

Views: 884

Answers (2)

If two classes need to import each others header files, you can use forward declarations.

The way this works is in the child header file you would set it up like so:

@class MyParentClass;  // This is the forward declaration.

@interface MyChildClass
@property (nonatomic, strong) MyParentClass *parent;
@end

In the child .m file, you would #import "MyParentClass.h" as usual. In MyParentClass.h, you can then just #import "MyChildClass.h"

Upvotes: 4

Chuck
Chuck

Reputation: 237040

You don't #import a class. You #import a file – invariably a header. Each of classes' .m files should import the other class's .h file and it will work fine.

Upvotes: 1

Related Questions