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



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

密钥:(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上。好像不是NSDictionary?知道为什么当NSDictionary位于属性列表的值字段中时,我无法检索它吗?我需要使用NSPropertySerialization吗?

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

是错误的,因为您没有指定正确的键。

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

最新更新