开发者

Cyclic Reference - protocols and subclasses

I'm getting some cyclic reference (I think) problems between a few classes that require imported headers due to either subclassing or protocol definitions. I can explain why things are set up this way but I'm not sure it's essential. Basically these classes are managing reciprocal to-many data relationships.

The layout is this:

Class A imports Class B because it's a delegate of Class B and needs its protocol definition.

Class B imports Class C because it's a subclass of Class C.

Class C imports Class A because it's a delegate of Clas开发者_开发百科s A and needs its protocol definition.

Here's some sample code that illustrates the problem. The errors I'm getting are as follows: In Class A - "Can't find protocol definition for Class_B_Delegate". In Class B - "Can't find interface declaration for Class C - superclass of Class B." In Class C - "Can't find protocol definition for Class_A_Delegate".

Class A header:

#import <Foundation/Foundation.h>
#import "Class_B.h"

@protocol Class_A_Delegate
@end

@interface Class_A : NSObject <Class_B_Delegate> {
}

@end

Class B header:

#import <Foundation/Foundation.h>
#import "Class_C.h"

@protocol Class_B_Delegate <NSObject>
@end

@interface Class_B : Class_C {
}

@end

Class C Header:

#import <Foundation/Foundation.h>
#import "Class_A.h"

@interface Class_C : NSObject <Class_A_Delegate> {
}

@end


You can use forward declarations to break dependency cycle. See Referring to Other Classes in the Objective-C Programming Guide.

So the Class C header should look like:

#import <Foundation/Foundation.h>

@protocol Class_A_Delegate;

@interface Class_C : NSObject <Class_A_Delegate> {
}

@end


i would say its bad layout that causes the cyclic referencing. try to restructure them and problem will go away.


In response to the suggestion I restructure the layout - here's the layout. It wouldn't fit in a comment.

View controller A manages a list of car objects and calls view controller B to add a car object. When B is finished it calls its delegate A to let it now it's added a car object. Now, a car object can have many driver objects, so when B is adding a car it can display a list of driver objects using view controller C, which is a subclass of view controller D. D displays driver objects similar to the way A displays car objects. C subclasses D to allow a selection type interface. Since D displays driver objects and a driver can have many cars, D calls view controller E which has functionality similar to C, allowing selection of car objects. E is a subclass of A.

I hope that's clear.


I ended up putting the protocol definitions in separate header files and that seemed to work.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜