我正在开发一个 iphone 应用程序,我需要有一些功能可以在我的类(class)中全局使用。
但是我该怎么做呢?
我刚刚尝试创建 functions.h
喜欢这个
#include <Foundation/Foundation.h>
- (void)printTest;
并且在 functions.m
#import "functions.h"
- (void)prinTest {
NSLog(@"test");
}
但它不起作用。我说:“方法定义不在@implementation 上下文中”。
最佳答案
首先请注意,Objective-C 语言是 C 语言的超集(这意味着混合使用它们绝对没有错)。
有两种方法。
#1 真正的全局函数:
声明一个全局 C 风格函数,它可以有 ObjC 逻辑(在定义中而不只是 C 风格逻辑)。
标题:
void GSPrintTest();
实现:
#import "functions.h"
#import <Foundation/Foundation.h>
void GSPrintTest() {
NSLog(@"test");
}
调用方式:
#import "functions.h"
...
GSPrintTest();
第三个(不好,但可能)选项是为您的方法向 NSObject 添加一个类别:
标题:
#import <Foundation/Foundation.h>
@interface NSObject(GlobalStuff)
- (void) printTest;
@end
实现:
#import "functions.h"
@implementation NSObject(GlobalStuff)
- (void) printTest {
NSLog(@"test");
}
@end
调用方式:
#import "functions.h"
...
[self printTest];
#2类方法:
在辅助类中创建一个带有 +
符号的类方法(而不是带有 -
符号的实例方法)。
标题:
#import <Foundation/Foundation.h>
@interface GlobalStuff : NSObject {}
+ (void)printTest;
@end
实现:
#import "functions.h"
@implementation GlobalStuff
+ (void) printTest {
NSLog(@"test");
}
@end
调用方式:
#import "functions.h"
...
[GlobalStuff printTest];
关于iphone - 如何在 Objective-C 中创建全局函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7294176/