Question

I'm building an application that will be reused by multiple clients. One difference in the application is the EventID. I dont want to change code everytime I create a new one of these applications, but instead use a configuration file of some sort and set the ID there and keep the code the same accessing this file. What is the best place to do this (plist)? and how do I access this key in code and globally if possible?

Was it helpful?

Solution

If you put your setting in your app's Info.plist file, you can access it as follows:

NSString *eventID = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"EventID"];

You can also store your value in a separate property list file (Settings.plist, for example), include it in your app's “Copy Bundle Resources” build phase, and access it like so:

NSString *settingsPath = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"plist"];
NSDictionary *settings = [NSDictionary dictionaryWithContentsOfFile:settingsPath];
NSString *eventID = [settings objectForKey:@"EventID"];

One way to make it easier to read your settings would be to provide access via a class:

@interface CNSSettings : NSObject

+ (NSString *)eventID;

@end

@implementation CNSSettings

+ (NSDictionary *)settingsDictionary
{
    static NSDictionary *_settingsDictionary = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        NSString *settingsPath = [[NSBundle mainBundle] pathForResource:@"Settings" ofType:@"plist"];
        _settingsDictionary = [NSDictionary dictionaryWithContentsOfFile:settingsPath];
    });

    return _settingsDictionary;
}

+ (NSString *)eventID
{
    return [[self settingsDictionary] objectForKey:@"EventID"];
}

@end

Using the class above, you would just have to do the following:

NSString *eventID = [CNSSettings eventID];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top