开发者

Circular references and warnings caused by forward declarations in Object C

开发者 https://www.devze.com 2023-02-20 20:24 出处:网络
I have two classes that reference each other and therefore a forward declaratio开发者_运维知识库n is required to avoid circular references.Because of the forward declaration I get all kinds of warning

I have two classes that reference each other and therefore a forward declaratio开发者_运维知识库n is required to avoid circular references. Because of the forward declaration I get all kinds of warnings when trying to reference the class name or properties of the class that has the forward declaration. Any suggestions? The key constraint is I need to preserve the ability to have the classes reference each other

ClassA.h

#import "ClassB.h"

@interface ClassA : NSObject {
    ClassB *class_b;
}
@end

ClassB.h

@class ClassA;

@interface ClassB : NSObject {
     ClassA *class_a;

}

@end

ClassB.m

#import "ClassB.h"


@implementation ClassB

-(void)method{
}
- (id)init
{
    (self = [super init]);
    class_a = [[ClassA alloc] init];
    return self;
}


@end

The warning I get is as follows:

ClassB.m:13: warning: receiver 'ClassA' is a forward class and corresponding @interface may not exist


In ClassB.m you need to #import "ClassA.h". The @class forward declaration is just for the header file.


The headers only need to know ClassA and ClassB exist and so a forward declaration works.

However in the implementation they need to know more about the other class. Thus in the implementation files you need to #import the other class. You don't have the an issue as the implementation of one class only needs to know the interface of the other,


In headers do not use import/include but use the @class directive. It basically tells "there is a class called X defined somewhere"

0

精彩评论

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

关注公众号