0

我正在尝试使用 .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 是空的。

4

1 回答 1

0

remove space here in item 6

[myDict objectForKey:@"Item6"];

and if this not works try this one

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");
}
于 2012-05-09T12:12:40.040 回答