在 Objective-C 中,如何制作一个所有人都可以访问的全局配置?
我是 Objective-C 和 iOS 开发的新手,我不确定我做得是否正确。无论如何,基本上我有一个文件 Configs.plist,目前它有两组 Keys:Value(Customer:Generic 和 Short_Code:Default)。我希望所有类都能轻松访问这些数据,因此我创建了这些:
Configs.h
extern NSString * const CUSTOMER;
extern NSString * const SHORT_CODE;
@interface Configs
+ (void)initialize;
+ (NSDictionary *)getConfigs;
@end
Configs.m
#import "Configs.h"
NSString * const CUSTOMER = @"Customer";
NSString * const SHORT_CODE = @"Short_Code";
static NSDictionary *myConfigs;
@implementation Configs
+ (void)initialize{
if(myConfigs == nil){
NSString *path = [[NSBundle mainBundle] pathForResource:@"Configs" ofType:@"plist"];
settings = [[NSDictionary alloc] initWithContentsOfFile:path];
}
}
+ (NSDictionary *)getConfigs{
return settings;
}
@end
并在测试文件 Test.m 上:
NSLog(@"Customer: %@", [[Configs getConfigs] objectForKey:CUSTOMER]);
NSLog(@"Short Code: %@", [[Configs getConfigs] objectForKey:SHORT_CODE]);
问题是,这种方法有效,但我想知道是否有更好的方法做这个。
I am new to Objective-C and iOS development and I'm not sure if I'm doing it right. Anyway, basically I have a file Configs.plist which, for now has two sets of Keys:Value (Customer:Generic and Short_Code:Default). I want these data to be easily accessible to all classes so I created these:
Configs.h
extern NSString * const CUSTOMER;
extern NSString * const SHORT_CODE;
@interface Configs
+ (void)initialize;
+ (NSDictionary *)getConfigs;
@end
Configs.m
#import "Configs.h"
NSString * const CUSTOMER = @"Customer";
NSString * const SHORT_CODE = @"Short_Code";
static NSDictionary *myConfigs;
@implementation Configs
+ (void)initialize{
if(myConfigs == nil){
NSString *path = [[NSBundle mainBundle] pathForResource:@"Configs" ofType:@"plist"];
settings = [[NSDictionary alloc] initWithContentsOfFile:path];
}
}
+ (NSDictionary *)getConfigs{
return settings;
}
@end
And on a the test file Test.m:
NSLog(@"Customer: %@", [[Configs getConfigs] objectForKey:CUSTOMER]);
NSLog(@"Short Code: %@", [[Configs getConfigs] objectForKey:SHORT_CODE]);
The thing is, this approach works but I want to know if there are better ways to do this.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
我认为只要你的配置在执行过程中不改变就很好。如果是这样,您最好使用单例将您的配置公开为属性,这样您就可以执行以下操作:
您仍然可以从 plist 初始化配置,或者实现编码协议以将其存储在 NSUserDefaults。
I think this is good as long as your configuration does not change during execution. If it does, you're better off with the singleton exposing your config as properties, so you would be able to do something like this:
You could still init the config from the plist, or implement coding protocol to store it in the NSUserDefaults.