tags:

views:

70

answers:

2

I have two classes (Test1 and Test2) that each have a property (test2 and test1 respectively) pointing to an instance of the other class. This means that Test1.m must import Test2.h and Test2.m must import Test1.h. The .h files must also have a forward declaration. Unfortunately, this means that I cannot access the attributes of test2 and test1 with dot notation. I can access them with message passing, but I should be able to use either notation. How can I resolve this problem?

Related

Test1

//Test1.h

@class Test2;

@interface Test1 : NSObject {
 Test2* test2;
 int a1;
}
@property (nonatomic, retain) Test2* test2;

-  (void)meth1;

@end

//Test1.m
#import "Test1.h"
#import "Test2.h"

@implementation Test1

@synthesize test2;

-  (void)meth1{
 test2.a2;//Request for member 'a2' in something not a structure or union
}

@end

Test2

//Test2.h
#import <Foundation/Foundation.h>

@class Test1;

@interface Test2 : NSObject {
 Test1 *test1;
 int a2;
}

@property (nonatomic, assign) Test1* test1;

-  (void)meth2;

@end

//Test2.m
#import "Test2.h"
#import "Test1.h"

@implementation Test2

@synthesize test1;

-  (void)meth2{
 test1.a1;//Request for member 'a1' in something not a structure or union
}

@end
+3  A: 

Adding properties for and synthesizing a1 & a2 seems to help.

blindJesse
+2  A: 

If you want to access a1 and a2 outside of the class they belong to, I'd strongly recommend defining them as properties.

However, if you really want to avoid message passing, you can define them as public in the header:

@interface Test2 : NSObject {
 Test1 *test1;
 @public 
   int a2;
}

and access them like this:

-  (void)meth1{
    test2->a2;
}
amrox
Ooph... I don't think public ivars are the right way to do this. They're generally discouraged unless you have a *very* good reason for exposing them (ie, your accessors are performance bottlenecks).
Dave DeLong
Thanks, I should have been clearer that I don't have anything against message passing, just that I should be able to use either dot notation or message passing notation
Casebash
@Dave Delong: I agree, which is why I prefaced by recommending to use properties.
amrox