Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to declare a function in Cocoa after the function using it?

I'm slowly building my application to a working state.

I'm using two functions called setCollection and addToCollection. These functions both accept NSArray as input.

I also have a function called add in which I use both of these functions. When I try to compile, Xcode shows an error:

'setCollection' undeclared (first use in this function)

I guess this has to do with the function called being defined below the active function. Another guess would be that the functions should be globalized to be useable inside my add function.

I'm normally a php coder. the way Php handles this is the first one. The functions called should be before the functions using them, because otherwise they just don't exist. Is there a way to make functions still to come available at runtime, or should I rearrange all functions to make them function properly?

like image 677
xaddict Avatar asked Feb 16 '26 03:02

xaddict


1 Answers

You can declare functions ahead of time as follows:

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
}

If you are creating a custom class, and these are member functions (usually called methods in Objective-C) then you would declare the methods in your class header and define them in your class source file:

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

}

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

@end


//MyClass.m:

#import "MyClass.h"

@implementation MyClass

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

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

@end


//some other source file

#import "MyClass.h"

//...

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

//...
like image 120
e.James Avatar answered Feb 17 '26 17:02

e.James