从属性列表中检索嵌套的NSDictionary

时间:2012-06-11 01:36:06

标签: iphone objective-c ios ios5

我想将数据保存在一个视图的属性列表中,并在另一个视图中检索它。我正在保存的数据结构如下所示:

键:( NSString) 价值(NSDictionary)

NSDictionary只包含键和值的字符串。每当按下一个按钮时,我都会触发此方法进行保存:

- (IBAction)saveRSSItem:(id)sender {

    NSMutableDictionary *dictionary;

    if ([[NSFileManager defaultManager] fileExistsAtPath:[self dataFilePath]]){
        dictionary = [[NSMutableDictionary alloc] initWithContentsOfFile:[self dataFilePath]];
    }
    else {
        dictionary = [[NSMutableDictionary alloc] init];
    }

    //Create Dictionary to store RSSItem information
    NSMutableDictionary *RSSdictionary = [[NSMutableDictionary alloc] init];

    if (self.selectedItem.title)
        [RSSdictionary setValue:@"title" forKey:self.selectedItem.title];

    if (self.selectedItem.summary)
        [RSSdictionary setValue:@"summary" forKey:self.selectedItem.summary];

    if (self.selectedItem.author)
        [RSSdictionary setValue:@"author" forKey:self.selectedItem.author];

    if (self.selectedItem.date)
        [RSSdictionary setValue:@"date" forKey:self.selectedItem.date];

    if (self.selectedItem.content)
        [RSSdictionary setValue:@"content" forKey:self.selectedItem.content];

    //Add saved RSSItem to dictionary
    [dictionary setValue:RSSdictionary forKey:self.selectedItem.title];

    //Overwrite the updated dictionary in the property list
    NSURL *url = [[NSURL alloc] initFileURLWithPath:[self dataFilePath]];
    [dictionary writeToURL:url atomically:YES];
}

当我尝试检索数据时,我会这样做:

NSDictionary *savedRSSItemsDictionary = [NSDictionary dictionaryWithContentsOfFile:[self propertyListFilePath]];
NSDictionary *RSSDictionary = [savedRSSItemsDictionary objectForKey:[savedRSSItemsArray objectAtIndex:indexPath.row]];

第一行检索根词典。第二行检索属性列表中第一行的值(NSDictionary)。

但是,我无法在RSSDictionary上使用valueForKey:方法。好像它不是NSDictionary?有什么想法,当它在属性列表的值字段中时,我无法检索NSDictionary?我需要使用NSPropertySerialization吗?

1 个答案:

答案 0 :(得分:0)

NSDictionary *savedRSSItemsDictionary = [NSDictionary 
          dictionaryWithContentsOfFile:[self propertyListFilePath]];
NSDictionary *RSSDictionary = 
    [savedRSSItemsDictionary objectForKey:[savedRSSItemsArray 
                                       objectAtIndex:indexPath.row]];

错误是因为您没有指定正确的密钥。

您应该使用NSArray存储数据。按字典中字段的值索引字典是个坏主意。