正确获取可转换的coredata元素

时间:2014-01-02 15:46:30

标签: ios objective-c core-data

EDIT2: 我的主要目标是使用下面的信息填写tableview,例如,每个单元格将包含地址和first_name。有没有一种简单的方法来填充我的观点?

好的,所以我无法正确加载已保存到coredata中的数据。我将字典/数组保存为可转换的coredata属性。这是我保存到coredata的nslog:

(
        {
        "ADD_CITY" = ABC;
        "ADD_LINE1" = "123 MAIN";
        "ADD_LINE2" = "";
        "ADD_STATE" = IA;
        "ADD_ZIP" = 50833;
        "BUSINESS_NAME" = "";
        "FIRST_NAME" = JOHN;
        "LAST_NAME" = DOE;
    },
        {
        "ADD_CITY" = ABCD;
        "ADD_LINE1" = "1234 MAIN";
        "ADD_LINE2" = "";
        "ADD_STATE" = IA;
        "ADD_ZIP" = 50833;
        "BUSINESS_NAME" = "";
        "FIRST_NAME" = JOE;
        "LAST_NAME" = SMITH;
    }
)

一切都很好,但是当我稍后尝试加载它时,问题出现了,这就是我正在做的事情:

 NSFetchRequest *fetchRequest2 = [NSFetchRequest fetchRequestWithEntityName:@"Locations"];
        NSEntityDescription *entity2 = [NSEntityDescription entityForName:@"Locations" inManagedObjectContext:self.managedObjectContext];


        fetchRequest2.resultType = NSDictionaryResultType;


        fetchRequest2.propertiesToFetch = [NSArray arrayWithObject:[[entity2 propertiesByName] objectForKey:@"location"]];

        [fetchRequest2 setPredicate:[NSPredicate predicateWithFormat:@"policy == %@", self.policy]];

        fetchRequest2.returnsDistinctResults = YES;

        self.dictionaries2 = [self.managedObjectContext executeFetchRequest:fetchRequest2 error:nil];
        NSLog (@"locations2: %@",self.dictionaries2);

我认为我得到一个“嵌套”词典?

上面的nslog:

locations2: (
        {
        location =         (
                         {
    "ADD_CITY" = ABC;
    "ADD_LINE1" = "123 MAIN";
    "ADD_LINE2" = "";
    "ADD_STATE" = IA;
    "ADD_ZIP" = 50833;
    "BUSINESS_NAME" = "";
    "FIRST_NAME" = JOHN;
    "LAST_NAME" = DOE;
},
    {
    "ADD_CITY" = ABCD;
    "ADD_LINE1" = "1234 MAIN";
    "ADD_LINE2" = "";
    "ADD_STATE" = IA;
    "ADD_ZIP" = 50833;
    "BUSINESS_NAME" = "";
    "FIRST_NAME" = JOE;
    "LAST_NAME" = SMITH;
}
        );
    }
)

我如何才能获得“位置”而不是额外的水平?

编辑:

也许更简单的方法就是删除获取结果的外层?如果是这样我该怎么做?

1 个答案:

答案 0 :(得分:4)

NSDictionaryResultType的抓取请求会返回一个字典数组 (每个获取的属性都有一个键/值对)。 如果您只对特定财产的价值感兴趣(在您的情况下“位置”) 你可以使用valueForKey

NSArray *locations = [self.dictionaries2 valueForKey:@"location"];

但是,从输出中看起来好像您只创建了一个单个核心数据 包含整个字典数组的对象。通常,人们会创建核心数据  每个位置的对象。要在表视图中显示数据,可以使用a NSFetchedResultsController