Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
616 views
in Technique[技术] by (71.8m points)

iphone - How to create global functions in Objective-C

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".

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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.

#1 Real global function:

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];

#2 class method:

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];

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...