I'm developing an iphone app and I need to have some functions to use globally in my classes.
But how can I do this?
I just tried to create functions.h
likes this
#include <Foundation/Foundation.h> - (void)printTest;
and in the functions.m
#import "functions.h" - (void)prinTest { NSLog(@"test"); }
but it doesn't work. Says me: "Method definition not in a @implementation context".
When you want a global function, just write a regular C function. The Objective-C syntax is meant to be used solely in the context of object methods.
void printTest() { NSLog(@"This is a test"); }
You also have to add the declaration in the functions.h
header:
void printTest();
First note that Objective-C language is a superset of C language (meaning there is absolutely nothing wrong with mixing them).
There are two approaches.
Declare a global C-style function, which can have ObjC logic (in definetion instead of just C-style logic).
Header:
void GSPrintTest();
Implementation:
#import "functions.h" #import <Foundation/Foundation.h> void GSPrintTest() { NSLog(@"test"); }
Call using:
#import "functions.h" ... GSPrintTest();
A third (bad, but possible) option would be adding a category to NSObject for your methods:
Header:
#import <Foundation/Foundation.h> @interface NSObject(GlobalStuff) - (void) printTest; @end
Implementation:
#import "functions.h" @implementation NSObject(GlobalStuff) - (void) printTest { NSLog(@"test"); } @end
Call using:
#import "functions.h" ... [self printTest];
Create a class method with +
sign, in helper class (instead of instance method with -
sign).
Header:
#import <Foundation/Foundation.h> @interface GlobalStuff : NSObject {} + (void)printTest; @end
Implementation:
#import "functions.h" @implementation GlobalStuff + (void) printTest { NSLog(@"test"); } @end
Call using:
#import "functions.h" ... [GlobalStuff printTest];
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With