I am implementing a application based on web services. In that I need to add a string as property in .plist and I need to get the value from the .plist whenever I need in the code.
Asked
Active
Viewed 2.4k times
22
-
possible duplicate of [getting data from plist to NSMutableArray and writing the NSMutableArray to same plist iPhone](http://stackoverflow.com/questions/9193363/getting-data-from-plist-to-nsmutablearray-and-writing-the-nsmutablearray-to-same) – Monolo Jul 15 '12 at 10:22
5 Answers
36
Here is a code sample:
NSString *path = [[NSBundle mainBundle] pathForResource: @"YourPLIST" ofType: @"plist"];
NSDictionary *dict = [NSDictionary dictionaryWithContentsOfFile: path];
id obj = [dict objectForKey: @"YourKey"];
jv42
- 8,440
- 4
- 39
- 62
-
1
-
Your plist file must be added to the project, then you must set its exact name (including case) in the code above. – jv42 Oct 14 '10 at 08:51
-
1@BenC.R.Leggiero Once you've executed the second line, you've got a regular `NSDictionary` that you can use as any other dictionary. – jv42 Apr 20 '15 at 16:33
21
NSBundle* mainBundle = [NSBundle mainBundle];
// Reads the value of the custom key I added to the Info.plist
NSString *value = [mainBundle objectForInfoDictionaryKey:@"key"];
//Log the value
NSLog(@"Value = %@", value);
// Get the value for the "Bundle version" from the Info.plist
[mainBundle objectForInfoDictionaryKey:@"CFBundleVersion"];
// Get the bundle identifier
[mainBundle bundleIdentifier];
Nikhil Dinesh
- 3,251
- 2
- 35
- 41
6
NSURL *url = [[NSBundle mainBundle] URLForResource:@"YOURPLIST" withExtension:@"plist"];
NSArray *playDictionariesArray = [[NSArray alloc ] initWithContentsOfURL:url];
NSLog(@"Here is the Dict %@",playDictionariesArray);
or you can use following also
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"Sample.plist"];
VSN
- 2,351
- 21
- 29
2
Get from plist is very simple.
NSString *path = [[NSBundle mainBundle] pathForResource:@"SaveTags" ofType:@"plist"];
if (path) {
NSDictionary *root = [NSDictionary dictionaryWithContentsOfFile:path];
}
If you want to add something to a plist, maybe you can find the answer here: How to write data in plist?
But if you only want save some message in you app, NSUserDefaults is the better way.
1
You can not do this. Any Bundle wether it is iOS or Mac OS is readonly, you can only read to it and you can't create files, write or do anything with the files in a bundle. This is part of the Security features of apple. You can use the NSDocumentsDirectory to writr and read your stuff you need for your app
Janosch Hübner
- 1,474
- 21
- 39