如何在Objective-C中创建全局函数问题,怎么解决
若以下回答无法解决问题,邀请你更新回答
1个回答
展开全部
Two options here. First is create a class method in a static class:
Header:
#import <Foundation/Foundation.h>
@interface GlobalStuff : NSObject {}
+ (void)printTest;
@end
Implementation:
#import "functions.h"
@implementation GlobalStuff
+ (void) printTest {
NSLog(@"test");
}
Call using:
#import "functions.h"
...
[GlobalStuff printTest];
The other option is to declare a global function instead of class:
Header:
void GSPrintTest();
Implementation:
#import <Foundation/Foundation.h>
#import "functions.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];
Header:
#import <Foundation/Foundation.h>
@interface GlobalStuff : NSObject {}
+ (void)printTest;
@end
Implementation:
#import "functions.h"
@implementation GlobalStuff
+ (void) printTest {
NSLog(@"test");
}
Call using:
#import "functions.h"
...
[GlobalStuff printTest];
The other option is to declare a global function instead of class:
Header:
void GSPrintTest();
Implementation:
#import <Foundation/Foundation.h>
#import "functions.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];
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询