Objective-C使用#import和继承 [英] Objective-C use of #import and inheritance
问题描述
我有一个假设的UIViewController类名为foo。 foo继承自类别栏和类别bar#import的A类,foo广泛使用的类。问题是,当我在foo中使用类A的实例时,我没有得到任何编译器错误,但我得到一个警告,例如,A类的实例不响应一个特定的方法。我必须显式#import ClassA.h到类'foo'?即使类foo扩展了扩展栏,它已经导入了它吗?
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.
推荐答案
这听起来像你有一个循环依赖问题。为了解决它,是的,每个实现文件( .m
)需要 #import
正确的头文件。但是,如果您尝试让头文件 #import
彼此,就会遇到问题。
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.
为了使用继承,你需要知道超类的大小,这意味着你需要 #import
它。对于其他事情,虽然,例如作为指针的成员变量,或作为参数或返回其他类型的方法,你实际上不需要类定义,所以你可以使用前向引用解决编译器错误。
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
这篇关于Objective-C使用#import和继承的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!