NSMutableDictionary initWithContentsOfFile - null

时间:2012-05-09 12:08:47

标签: iphone ios

我正在尝试使用.plist的内容创建NSMutableDictionary。我有以下代码:

NSString *myFile = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
NSMutableDictionary* myDict = [[NSMutableDictionary alloc]initWithContentsOfFile:myFile];
NSObject *randomWord = [myDict objectForKey:@"Item 6"];
NSLog(@"%@", randomWord);

myFile和myDict被填充(非空),但是当想要打印randomWord(或myDict)时,它会打印“(null)”。

我到处寻找。我做错了什么?

编辑:

self    MainViewController *const   0x068c0d60
myDict  NSMutableDictionary *   0x0000586c
myFile  NSString *  0x068c31f0

和NSLog:

2012-05-10 12:26:22.302 project2[681:f803] (null)

所以似乎myFile和myDict已经填满了,但randomWord不是吗?

编辑#2:

NSLog(@“%@”,myDict)打印:

2012-05-10 14:15:17.016 project2[2641:f803] (null)

所以你说得对,myDict是空的。

1 个答案:

答案 0 :(得分:0)

删除第6项中的空格

[myDict objectForKey:@"Item6"];

如果这不起作用,试试这个

NSString *path = [[NSBundle mainBundle] pathForResource:@"words" ofType:@"plist"];
NSData* data = [NSData dataWithContentsOfFile:path];
NSMutableArray* array = [NSPropertyListSerialization propertyListFromData:data
                                                         mutabilityOption:NSPropertyListImmutable
                                                                   format:NSPropertyListXMLFormat_v1_0
                                                         errorDescription:NULL];
if (array) {
  NSMutableDictionary* myDict = [NSMutableDictionary dictionaryWithCapacity:[array count]];
  for (NSDictionary* dict in array) {
    State* state = [[State alloc] initWithDictionary:dict];
    [myDict setObject:state forKey:state.name;
    [state release];
  }
  NSLog(@"The count: %i", [myDic count]);
} else {
  NSLog(@"Plist does not exist");
}