0

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.

Slayter
  • 1,172
  • 1
  • 13
  • 26
  • 1
    You can write the #import in .m file instead of .h in child class. there will not be any issue – Sumanth Jan 23 '13 at 06:01
  • 3
    1) You will need to use forward declarations in at least one of the header files 2) this s bad design, you should be using delegates. – Perception Jan 23 '13 at 06:04

2 Answers2

4

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"

Kendall Helmstetter Gelner
  • 74,769
  • 26
  • 128
  • 150
  • This seems like it will work. Forward declarations were never something I learned but this makes sense. – Slayter Jan 23 '13 at 13:31
1

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.

Chuck
  • 234,037
  • 30
  • 302
  • 389