0

我有一个名为 DataManager 的单例类。这个类被其他几个类用来处理加载和保存 plist 文件。

我正在添加 DataManager 保存屏幕截图和 plist 文件的功能。这需要我加载我希望截屏的视图。我正在加载的视图来自导入 DataManager 的控制器。

显然这是循环依赖,所以我使用了:

@class GardenView;

但是,这导致了以下错误:

  • 类消息的接收者“GardenView”是前向声明
  • 接收器类型“GardenView”例如消息是转发
  • 在转发类中找不到声明属性“边界”
  • 在转发类对象“GardenView”中找不到对象“GardenView”属性“层”

这似乎找不到从 UIView 超类继承的属性。前向类声明是这样吗?

如果我使用标准的#import 而不是@class,我会得到:

  • 解析问题:预期 A 类型

对于 GardenView 中引用 Plant 的方法(我可以很好地导入):

- (void) addPlantToView: (Plant*) plant;
- (void) addPlantToGarden: (Plant*) plant;
- (void) addPlantToViewAndGarden: (Plant*) plant;

Plant 类确实导入了 DataManager,但如果我将其更改为 @class,我会得到:

  • 选择器“sharedDataManager”没有已知的类方法

这个问题的解决方案是什么?类方法在头文件(+sharedDataManager)中。我做错了什么吗?

4

1 回答 1

4

You haven't made it clear where exactly you're doing the imports vs @class. And I think that's causing confusion. Here's what you want to do:

  • In GardenView.h, use @class Plant
  • In Plant.h, use @class GardenView
  • In GardenView.m, use #import "Plant.h"
  • In Plant.m, use #import "GardenView.m"

This breaks the circular dependency in the headers, but still allows the implementations to see the full information of the dependent class.

Now the reason why @class alone isn't sufficient is because all @class Foo does is it tells the compiler "There exists a class named Foo", without telling it anything at all about the class. The compiler doesn't know its methods. It doesn't know its superclass. All it knows is if it sees the token Foo, then that represents a class type. You can use this in header files so you can refer to the class in arguments and return types, but in order to actually do anything with values of that type you still need the full #import. But you can put that #import in the .m file without any problem.

The only time you need #import instead of @class in your header is if you want to inherit from the class in question. You cannot inherit from forward-declared classes, so you need the full #import. Of course, you may also need the #import if you need access to other types defined in the same header (e.g. structs, enums, etc.), but that's less common in obj-c.

于 2012-12-10T20:37:11.403 回答