我有一个像这样组成的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>1</key>
<dict>
<key>2</key>
<array>
<array>
<string>a</string>
<integer>1</integer>
</array>
<array>
<string>b</string>
<integer>0</integer>
</array>
<array>
<string>c</string>
<string>0</string>
</array>
</array>
</dict>
</dict>
</plist>
我尝试读取此文件,但我不明白错误在哪里:
NSError *error;
NSMutableArray *result=[[NSMutableArray alloc] initWithCapacity:1];
NSString *pList = @"a.plist"; //
NSString *plistPath;
//path
NSString *rootPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
plistPath = [rootPath stringByAppendingPathComponent:pList];
//check if the path exist
BOOL success;
NSFileManager *fileManager = [NSFileManager defaultManager];
success = [fileManager fileExistsAtPath:plistPath];
if (!success) {
NSString *path = [[NSBundle mainBundle] pathForResource:pList ofType:@""];
[fileManager copyItemAtPath:path toPath:plistPath error:&error];
NSLog(@"error");
}
//read the dictionary
NSDictionary *temp = [[NSDictionary alloc] initWithContentsOfFile:plistPath];
//get value for key of the dictionary
result=[temp valueForKey:@"1"];
NSMutableArray *tmp = [result objectAtIndex:1]; //this give me error
NSLog(@"n %d", [tmp count]);
...
if(!temp) [temp release];
答案 0 :(得分:1)
在根词典中,键1
指向词典。您正尝试将其分配给result
NSMutableArray
变量。所以你得到了错误。此外,您正在创建将实例分配给result
,然后重新分配它。这是内存泄漏。你将从plist获得的数组将是一个不可变的数组。如果您打算对其进行更改,则必须创建可变副本。