在Objective-C中,如何进行所有人都可以访问的全局配置?

时间:2012-02-10 07:38:32

标签: ios objective-c configuration global-variables plist

我是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]);

问题是,这种方法有效,但我想知道是否有更好的方法来做到这一点。

1 个答案:

答案 0 :(得分:2)

我认为只要你的配置在执行期间没有改变,这就很好。如果是这样的话,你最好将单例暴露给你的配置作为属性,这样你就能做到这样的事情:

[[Config shared] customer];
[[Config shared] setShortCode:@"CODE"];

你仍然可以从plist初始化配置,或者实现编码协议将其存储在NSUserDefaults中。