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

states = [states init];

这是init方法在各州:

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

    return self;
}

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

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

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


确保单元方法的原型在.h文件中。

因为调用方法的位置比定义方法的位置高,所以会得到这条消息。或者,您可以重新安排方法,以便调用者在文件中的位置低于他们调用的方法。


这基本上意味着您需要导入包含国家声明的.h文件。

但是,您的代码中还有许多其他错误。

你在-init一个对象而没有+alloc它。这是行不通的 你把一个对象声明为非指针类型,这也不行 在-init中没有调用[super init]。 您已经在头文件中使用@class声明了该类,但从未导入该类。


你正在使用

States states;

你应该在哪里使用

States *states;

init方法应该是这样的

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

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

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

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


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.


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

第一个是您所引用的,它可以通过在.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

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


我试图使用@class "Myclass.h"。

当我把它改为#import“Myclass.h”时,它工作得很好。


如果你在Objective C中尝试使用Swift类或方法时遇到这个错误:你忘记了Apple在图中定义的两个步骤之一:

例子:

错误显示在您的测试中。m文件:

类消息的接收者'MyClass'是一个前向声明

Obj-C文件:

步骤1:检查Test.h是否有

@class MyClass;

第二步:在Build Settings中找到*-Swift.h的文件名(找Objective-C Generated Interface Header name)。名字应该是mymodule - swift。h

步骤3:检查Test。M导入上面的头文件

#import <MyModule/MyModule-Swift.h>

在Swift文件中:

确保MyClass(或它的基类)继承了NSObject类。 确保@objc在你想从Obj-C调用的每个方法之前。 同样,检查目标成员部分(在文件检查器中)。