0

I want to read in my .plist but my NSLog is equal to "(null)". Here is my code:

NSMutableDictionary* plistDict = [[NSMutableDictionary alloc] initWithContentsOfFile:@"data.plist"];

NSLog(@"%@", [plistDict objectForKey:@"id"]);

And here is my .plist: http://cl.ly/image/2e3P3Q1z2Z1T

user1269586
  • 372
  • 1
  • 6
  • 27

1 Answers1

2

Your path is wrong. If your plist is in your app resources, then you have to use NSBundle to get it's absolute path.

NSString *path = [[NSBundle mainBundle] pathForResource:@"data" ofType:@"plist"];
NSMutableDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path] 
                              mutableCopy];

If it's in your app's documents folder, you can do this:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
NSString *path = [basePath stringByAppendingPathComponent:@"data.plist"];
NSMutableDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy];

Note that a dictionary or array loaded from a plist is always immutable. You have to create a mutable copy.

DrummerB
  • 39,814
  • 12
  • 105
  • 142
  • My plist is in _~/Library/Application Support/iPhone Simulator/iOS/Applications/MY-APP/Documents_ but this code doesn't work, any idea? – user1269586 Oct 28 '12 at 20:22
  • See [this](http://stackoverflow.com/a/6907432/343340) on how to get the documents folder path. And see my updated answer. – DrummerB Oct 28 '12 at 20:31
  • NSLog is equal to "(null)" again... But my code looks great: `- (void)viewDidAppear:(BOOL)animated { NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, SUserDomainMask, YES); NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil; NSString *path = [basePath stringByAppendingPathComponent:@"data-article-itiap.plist"]; NSMutableDictionary *dict = [[NSDictionary dictionaryWithContentsOfFile:path] mutableCopy]; NSLog(@"%@", [dict objectForKey:@"id"]); }` – user1269586 Oct 28 '12 at 21:11
  • Either there is no key `id` in your dict. Or the file doesn't exist. Log `path` and see if the file is really at that location. – DrummerB Oct 28 '12 at 21:44
  • I really don't understand, my code is great and I got the key "id" (string) in my dictionary. Maybe it's bugging because my root is an array? – user1269586 Oct 28 '12 at 22:21
  • Of course that's the problem. You should have said that earlier. See [my answer to your other post](http://stackoverflow.com/a/13113756/343340). – DrummerB Oct 28 '12 at 22:42