在我的iOS5应用程序中,我有NSObject States类,并试图初始化它:

states = [states init];

这是init方法在各州:

- (id) init
{
    if ((self = [super init]))
    {
        pickedGlasses = 0;
    }

    return self;
}

但是在lines states = [states init]中有错误;

接收端类型为“States”的实例消息是前向声明

这是什么意思?我做错了什么?


当前回答

I got this sort of message when I had two files that depended on each other. The tricky thing here is that you'll get a circular reference if you just try to import each other (class A imports class B, class B imports class A) from their header files. So what you would do is instead place a forward (@class A) declaration in one of the classes' (class B's) header file. However, when attempting to use an ivar of class A within the implementation of class B, this very error comes up, merely adding an #import "A.h" in the .m file of class B fixed the problem for me.

其他回答

I got this sort of message when I had two files that depended on each other. The tricky thing here is that you'll get a circular reference if you just try to import each other (class A imports class B, class B imports class A) from their header files. So what you would do is instead place a forward (@class A) declaration in one of the classes' (class B's) header file. However, when attempting to use an ivar of class A within the implementation of class B, this very error comes up, merely adding an #import "A.h" in the .m file of class B fixed the problem for me.

你正在使用

States states;

你应该在哪里使用

States *states;

init方法应该是这样的

-(id)init {
  if( (self = [super init]) ) {
      pickedGlasses = 0;
  }
  return self;
}

最后,当你要为States类创建对象时你应该这样做。

State *states = [[States alloc] init];

我并不是说这是最好的方法。但是它可以帮助您理解初始化对象的基本用法。

有两个相关的错误消息可能告诉您声明和/或导入有问题。

第一个是您所引用的,它可以通过在.m(或.pch文件)中不放置#import而在.h中声明@类来生成。

第二个你可能会看到,如果你在States类中有一个方法:

- (void)logout:(NSTimer *)timer

添加#import后是这样的:

“state”没有可见的@接口声明选择器“logout:”

如果看到这种情况,您需要检查是否在您正在导入或转发的类的.h文件中声明了“注销”方法(在本例中)。

所以在你的例子中,你需要一个:

- (void)logout:(NSTimer *)timer;

在States类的.h中使一个或两个相关错误消失。

检查是否导入了抛出此错误的类的头文件。

FWIW,当我在现有项目中实现核心数据时,我得到了这个错误。结果我忘了把CoreData.h链接到我的项目。我已经在我的项目中添加了CoreData框架,但是通过在我的预编译头中链接到框架来解决这个问题,就像苹果的模板一样:

#import <Availability.h>

#ifndef __IPHONE_5_0
#warning "This project uses features only available in iOS SDK 5.0 and later."
#endif

#ifdef __OBJC__
    #import <UIKit/UIKit.h>
    #import <Foundation/Foundation.h>
    #import <CoreData/CoreData.h>
#endif