0

我正在使用此代码将内容添加到 plist 中:

//////////// Save data into plist /////////////////
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:@"datatesting.plist"];
NSLog(@"path='%@'",path);

NSFileManager *nfm = [[NSFileManager alloc] init];
if([nfm fileExistsAtPath:path])
{
    // if file exists, get its contents, add more entries and write back
    NSMutableArray *array = [[NSMutableArray alloc] initWithContentsOfFile:path];
    NSArray *keys = [NSArray arrayWithObjects:@"Title",@"Description",@"Coordinate",nil]; 

    [array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%@",titlestring],[NSString stringWithFormat:@"%@",descriptionstring],[NSString stringWithFormat:@"%@",coordinadastring], nil] forKeys:keys]]; 
    NSLog(@"modified array=%@",array);
    BOOL ok = [array writeToFile:path atomically:YES];
    if(!ok){
        NSLog(@"Unable to write appended file");
        return;
    }

} else {

    // if file doesn't exist, create a new one
    NSMutableArray *array = [[NSMutableArray alloc] init];
    NSArray *keys = [NSArray arrayWithObjects:@"Title",@"Description",@"Coordinate",nil]; 
    [array addObject:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:[NSString stringWithFormat:@"%@",titlestring],[NSString stringWithFormat:@"%@",descriptionstring],[NSString stringWithFormat:@"%@",coordinadastring], nil] forKeys:keys]]; 
    NSLog(@"new array=%@",array);
    BOOL ok = [array writeToFile:path atomically:YES];
    if(!ok){
        NSLog(@"Unable to write new file");
        return;
    }
}    

现在我在使用 plist 的内容时遇到了问题。所以我的两个问题是: - 当前 plist 的字典的键是什么?- 在 Tableview 中读取内容的方法是什么?

4

1 回答 1

1

你有一个字典数组。您需要迭代数组的内容,然后查看每个字典。您可以使用块枚举器或较旧的 for() 样式来执行此操作。我现在将使用后者,因为您可能不知道块。

NSArray *array = ...; // read in the array from the file
for(NSDictionary *dict in array) {
  NSString *title = [dict objectForKey:@"Title"];
  ... etc
}

当你想在 tablview 中显示这些数据时,行数就是字典的数量(即 [array count])。如果您只想显示每个单元格的标题,您将获取单元格行号,然后通过 [array objectAtIndex:cellRow]) 获取字典,然后像上面一样拉出标题。

于 2012-08-08T11:50:36.220 回答