Cyclic Reference - Protocols and Subclasses

I get some circular references (I think) between several classes that require imported headers due to either a subclass definition or a protocol definition. I can explain why everything is set up in this way, but I'm not sure if this is important. Basically, these classes control interdependent data relationships.

The layout is as follows:
Class A imports class B because it is a delegate of class B and needs a protocol definition.
Class B imports class C because it is a subclass of class C.
Class C imports class A because it is a delegate of class A and needs a protocol definition.

Here is sample code that illustrates the problem. The errors I get are the following: In class A - "Cannot find protocol definition for Class_B_Delegate". In class B - "Cannot find interface declaration for class C - superclass of class B." In class C, "Cannot find protocol definition for Class_A_Delegate."

Class A Title:

#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
+3
source share
4 answers

I ended up placing protocol definitions in separate header files and it seemed to work.

0
source

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

, C :

#import <Foundation/Foundation.h>

@protocol Class_A_Delegate;

@interface Class_C : NSObject <Class_A_Delegate> {
}

@end
+3

, . , .

0

- . .

A B , . B , A, . -, , B , -, C , D. D. , , A . C D, . D , , D E, , C, . E A.

, .

0
source

Source: https://habr.com/ru/post/1730335/


All Articles