NSArray 如果文件无法打开或文件内容无法解析成数组,则返回值为 nil。
我怀疑问题是您需要将内容放在 NSDictionary 而不是 NSArray 中
NSDictionary *theDict = [NSDictionary dictionaryWithContentsOfFile:plistFile];
Edit.Further to my answer
NSMutableArray *mutableArray =[[NSMutableArray alloc] initWithObjects:nil];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"animals" ofType:@"plist"]];
//--get parent dictionary/Array named animals which holds the animals dictionary items
NSDictionary *parentDictionary = [mainDictionary objectForKey:@"animals"];
//---enumerate through the dictionary objects inside the parentDictionary
NSEnumerator *enumerator = [parentDictionary objectEnumerator];
id value;
while ((value = [enumerator nextObject])) {
if ([[value valueForKey:@"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]])
{
[mutableArray addObject:[value valueForKey:@"name"]];
}
}
如果动物字典不在父字典或数组中,请使用类似的东西
NSMutableArray *mutableArray =[[NSMutableArray alloc] initWithObjects:nil];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"animals" ofType:@"plist"]];
//---enumerate through the dictionary objects
NSEnumerator *enumerator = [mainDictionary objectEnumerator];
id value;
while ((value = [enumerator nextObject])) {
if ([[value valueForKey:@"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]])
{
[mutableArray addObject:[value valueForKey:@"name"]];
}
}
编辑。 1.
用这个 plist 试试。
确保使用纯文本编辑器将其粘贴到并保存为 plist 文件
编辑.2。
我现在更新了我的 plist 以匹配你的。虽然另一个工作。我觉得我们使用相同的会更有意义。
<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
<key>Whale</key>
<dict>
<key>name</key>
<string>Whale</string>
<key>isMale</key>
<true/>
<key>color</key>
<string>blue</string>
<key>maxAge</key>
<integer>8</integer>
<key>minAge</key>
<integer>3</integer>
</dict>
<key>Dolphin</key>
<dict>
<key>maxAge</key>
<integer>20</integer>
<key>name</key>
<string>Dolphin</string>
<key>isMale</key>
<false/>
<key>color</key>
<string>blue</string>
<key>minAge</key>
<integer>15</integer>
</dict>
</dict>
</plist>
另外,这里有另一个例子展示了如何比较布尔值和数字
NSMutableArray *theAnimalMatched =[[NSMutableArray alloc] initWithObjects:nil];
NSDictionary *mainDictionary = [NSDictionary dictionaryWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"data1" ofType:@"plist"]];
//---enumerate through the dictionary objects inside the rootDictionary
NSEnumerator *enumerator = [mainDictionary objectEnumerator];
id returnValue;
while ((returnValue = [enumerator nextObject])) {
if ( [[returnValue valueForKey:@"isMale" ] boolValue] && [[returnValue valueForKey:@"minAge"] isEqualToNumber:[NSNumber numberWithInt:3]] && [[returnValue valueForKey:@"color"] isEqualToString:@"blue"] )
{
[theAnimalMatched addObject:[returnValue valueForKey:@"name"]];
}
}