Objective-C use of #import and inheritance

强颜欢笑 提交于 2019-12-22 05:52:22

问题


I have a hypothetical UIViewController class named "foo". foo inherits from class bar and class bar #import's "Class A", a class which foo uses extensively. The problem is, when I'm using an instance of class A in foo, I don't get any compiler errors, but I do get a warning for instance, that an instance of Class A does not respond to a particular method. Do I have to explicitly #import ClassA.h into class 'foo'? even though class foo extends extends bar, which already imports it?

Hope that's not too confusing. Let me know if I need to clear anything up.


回答1:


It sounds like you have a circular dependency issue. In order to resolve it, yes, each imlementation file (.m) needs to #import the proper header file. However, if you try to have the header files #import each other, you'll run into problems.

In order to use inheritance, you need to know the size of the superclass, which means you need to #import it. For other things, though, such as member variables which are pointers, or methods which take as a parameter or return the other type, you don't actually need the class definition, so you can use a forward reference to resolve the compiler errors.

// bar.h
@class A;  // forward declaration of class A -- do not to #import it here

@interface bar : UIViewController
{
    A *member;  // ok
}

- (A) method:(A)parameter;  // also ok
@end

// bar.m
#import "bar.h"
#import "A.h"

// can now use bar & A without any errors or warnings


来源:https://stackoverflow.com/questions/575160/objective-c-use-of-import-and-inheritance

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!