我想创建一个包含可从所有项目访问的静态值的类。
伪代码:
class Constants:
constant String API_URL : "http://api.service.com"
constant Integer SOME_VALUE : 7
我如何使用 Objective-C
做到这一点?
最佳答案
您的问题的答案是 extern keyword 。我将使用示例向您解释。在项目中添加 objective c 类并将它们命名为 Common ,现在在 Common.h 中
@interface Common : NSObject
extern NSString *SiteApiURL;
@end
在使用 extern 关键字定义了 NSString 类的实例之后,您需要做的是切换到 Common.m 类并初始化 NSString (SiteApiURL) 的值
#import "Common.h"
@implementation Common
NSString *SiteApiURL = @"http://api.service.com";
@end
像这样在 project-Prefix.pch 文件中导入 Common.h 类
#import <Availability.h>
#ifndef __IPHONE_3_0
#warning "This project uses features only available in iOS SDK 3.0 and later."
#endif
#ifdef __OBJC__
#import <UIKit/UIKit.h>
#import <Foundation/Foundation.h>
#import "Common.h"
#endif
全部完成,现在您可以在整个项目的任何地方使用对象“SiteApiURL”,而无需在任何地方导入任何类,即您可以直接在项目的任何地方使用这个变量。
关于objective-c - 在 Objective-C 中定义静态常量值的类,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16082275/