Strange bug with plist

喜夏-厌秋 提交于 2019-12-12 02:09:37

问题


I got a very strange bug when I'm trying to read my plist. My plist looks like :

Root (Array)
            Item 0 (Dictionary)
                              title (String)

I want to display title in the log, so I did the code bellow:

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];

NSLog(@"%@", [dict objectForKey:@"title"]);

NSLog(@"Path to plist: %@", path);

With this code, NSLog(@"%@", [dict objectForKey:@"title"]); is equal to "(null)"...

My plist is in my app's documents folder, and the log of path return the good path to my plist.

Help me please :)


回答1:


The root of your plist is an array but you read it into a dictionary, thats won't work.

You should:

  • read the plist into an array
  • get item 0 (objectAtIndex:0) -> this is a dictionary
  • on this dictionary you can perform objectForKey ...



回答2:


As @Tom said, (and as you said yourself in your first code block) the root of the plist is an array.

You can load an array very similarly using:

NSArray *array = [NSArray arrayWithContentsOfFile:path];

Then you can access the item at index 0 (the dictionary) like this:

NSDictionary *dict = [array objectAtIndex:0];

Or since Xcode 4.4 with thew new array literals:

NSDictionary *dict = array[0];

And then log the title as you already tried:

NSLog(@"%@", [dict objectForKey:@"title"]);

Or with the new syntax:

NSLog(@"%@", dict[@"title"]);


来源:https://stackoverflow.com/questions/13113681/strange-bug-with-plist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!