user2924482
user2924482

Reputation: 9140

Mac OSX How can I add plist to bundle and modify the plist

I have a plist and I copy the plist to my xcode project but it seems like the file is not in bundle:

NSDictionary *dict = [[NSBundle mainBundle] infoDictionary];
nslog (@"dict %@",dict);

but the file plist file is not showing. Question, how can I add the file to project in a way to see in the bundle? also any of you knows how can I modify the plist and save the changes?

I'll really appreciated your help

P.S. I'm using Xcode 5.

Upvotes: 3

Views: 2142

Answers (3)

Neha
Neha

Reputation: 1751

You can create a plist file in your bundle and modify its contents as:

NSString *bundlePath = [[NSBundle mainBundle]bundlePath]; //Path of your bundle
NSString *path = [bundlePath stringByAppendingPathComponent:@"MyPlist.plist"]; 
NSFileManager *fileManager = [NSFileManager defaultManager];

NSMutableDictionary *data;

if ([fileManager fileExistsAtPath: path]) 
{
    data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];  // if file exist at path initialise your dictionary with its data
}
else
{
    // If the file doesn’t exist, create an empty dictionary
    data = [[NSMutableDictionary alloc] init];
}

//To insert the data into the plist
int value = 5;
[data setObject:[NSNumber numberWithInt:value] forKey:@"value"];
[data writeToFile: path atomically:YES];
[data release];

//To retrieve the data from the plist
NSMutableDictionary *savedData = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
int savedValue;
savedValue = [[savedData objectForKey:@"value"] intValue];
NSLog(@"%i",savedValue);

Upvotes: 4

Parag Bafna
Parag Bafna

Reputation: 22930

infoDictionary will return Info.plist file. You should use pathForResource:ofType: method of NSBundle class.

NSString *commonDictionaryPath;
if (commonDictionaryPath = [[NSBundle mainBundle] pathForResource:@"CommonDictionary" ofType:@"plist"])  {
    theDictionary = [[NSDictionary alloc] initWithContentsOfFile:commonDictionaryPath];
}

How can I add plist to bundle
Drag your plist to "Copy Bundle Resources" phase of your build target

modify the plist
Copy the plist to your app's Documents folder and modify it there.

Upvotes: 2

Mihir Mehta
Mihir Mehta

Reputation: 13843

this should work

     NSString*pListDictPath = [[NSBundle mainBundle] pathForResource:@"yourPlistName" ofType:@"plist" inDirectory:@"YourDirectory"];
     if()
     {
            NSDictionary *theDictionary = [[NSDictionary alloc] initWithContentsOfFile:pListDictPath ];
     }

Upvotes: 0

Related Questions