如何在使用函数后在Cocoa中声明一个函数?

xad*_*ict 3 xcode cocoa declaration function

我正在慢慢地将我的应用程序构建到一个工作状态.

我正在使用两个叫做setCollection和的函数addToCollection.这些功能都接受NSArray为输入.

我也有一个函数调用add,我使用这两个函数.当我尝试编译时,Xcode显示错误:

'setCollection'未声明(首次在此函数中使用)

我想这与在活动函数下定义的函数有关.另一个猜测是函数应该全局化,以便在我的add函数中可用.

我通常是一个php编码器.Php处理这个问题的方式是第一个.调用的函数应该在使用它们的函数之前,否则它们就不存在了.有没有办法让函数在运行时仍然可用,或者我应该重新排列所有函数以使它们正常运行?

e.J*_*mes 8

您可以提前声明函数,如下所示:

void setCollection(NSArray * array);
void addToCollection(NSArray * array);

//...

// code that calls setCollection or addToCollection

//...

void setCollection(NSArray * array)
{
    // your code here
}

void addToCollection(NSArray * array)
{
    // your code here
}
Run Code Online (Sandbox Code Playgroud)

如果要创建自定义类,并且这些是成员函数(通常在Objective-C中称为方法),那么您将在类头中声明方法并在类源文件中定义它们:

//MyClass.h:
@interface MyClass : NSObject
{

}

- (void)setCollection:(NSArray *)array;
- (void)addToCollection:(NSArray *)array;

@end
Run Code Online (Sandbox Code Playgroud)


//MyClass.m:

#import "MyClass.h"

@implementation MyClass

- (void)setCollection:(NSArray *)array
{
    // your code here
}

- (void)addToCollection:(NSArray *)array
{
    // your code here
}

@end
Run Code Online (Sandbox Code Playgroud)


//some other source file

#import "MyClass.h"

//...

MyClass * collection = [[MyClass alloc] init];
[collection setCollection:someArray];
[collection addToCollection:someArray];

//...
Run Code Online (Sandbox Code Playgroud)


mou*_*iel 5

如果你的函数是全局的(不是类的一部分),你只需要在使用前发出声明,就像eJames建议的那样.

如果函数实际上是方法(类的一部分),则必须在实现之前声明类的匿名类,并将方法声明放在此接口中:

@interface Myclass()
- (void) setCollection:(NSArray*)array;
- (void) addToCollection:(NSArray*)array;
@end

@implementation Myclass

// Code that calls setCollection or addToCollection

- (void) setCollection:(NSArray*)array
{
    // your code here
}

- (void) addToCollection:(NSArray*)array
{
    // your code here
}

@end
Run Code Online (Sandbox Code Playgroud)

这样,您就不需要在主界面中公开您的函数了MyClass.