如何在Objective-C中创建全局函数 [英] How to create global functions in Objective-C
本文介绍了如何在Objective-C中创建全局函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在开发一款iphone应用程序,我需要在我的课程中使用全局功能。
I'm developing an iphone app and I need to have some functions to use globally in my classes.
但我该怎么办呢?
我刚尝试创建 functions.h
喜欢这个
#include <Foundation/Foundation.h>
- (void)printTest;
和 functions.m
#import "functions.h"
- (void)prinTest {
NSLog(@"test");
}
但它不起作用。我说:方法定义不在@implementation上下文中。
but it doesn't work. Says me: "Method definition not in a @implementation context".
推荐答案
这里有两个选项。首先是在静态类中创建一个类方法:
Two options here. First is create a class method in a static class:
标题:
#import <Foundation/Foundation.h>
@interface GlobalStuff : NSObject {}
+ (void)printTest;
@end
实施:
#import "functions.h"
@implementation GlobalStuff
+ (void) printTest {
NSLog(@"test");
}
使用以下方式致电:
#import "functions.h"
...
[GlobalStuff printTest];
另一种选择是声明一个全局函数而不是类:
The other option is to declare a global function instead of class:
标题:
void GSPrintTest();
实施:
#import <Foundation/Foundation.h>
#import "functions.h"
void GSPrintTest() {
NSLog(@"test");
}
使用以下方式致电:
#import "functions.h"
...
GSPrintTest();
第三种(不好但可能)选项是为您的方法添加NSObject类别:
A third (bad, but possible) option would be adding a category to NSObject for your methods:
标题:
#import <Foundation/Foundation.h>
@interface NSObject(GlobalStuff)
- (void) printTest;
@end
实施:
#import "functions.h"
@implementation NSObject(GlobalStuff)
- (void) printTest {
NSLog(@"test");
}
@end
使用以下方式拨打电话:
Call using:
#import "functions.h"
...
[self printTest];
这篇关于如何在Objective-C中创建全局函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文