【问题标题】:How to extract data from a NSArray fill with NSDictionary?如何从使用 NSDictionary 填充的 NSArray 中提取数据?
【发布时间】:2010-11-23 08:55:17
【问题描述】:

我尝试用核心数据发出一种“sql distinct”请求, 所以我像这样设置我的 NSFetchrequest

NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
[fetchRequest setEntity:[NSEntityDescription entityForName:@"my_table" inManagedObjectContext:managedObjectContext]];

[fetchRequest setResultType:NSDictionaryResultType];
[fetchRequest setReturnsDistinctResults:YES];
[fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"first_property",@"second_property",nil]];

// Execute the fetch
NSError *error;
table_dom = [[NSArray alloc] init];
table_dom = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
[fetchRequest release];

这对我来说看起来不错,但我想我用 NSDictionary 检索一个 NSArray 填充,是这样吗?

所以我的问题是如何从 table_dom 中提取数据用于 tableview,我尝试了很多东西但没有一个有效?

它必须是: cell.textLabel.text = //“第一个属性”和 cell.detailTextLabel.text = //"second_property"

或者为了简单起见,我可以使用 setReturnsDistinctResults 而不是 NSDictionary 检索对象吗?

谢谢

【问题讨论】:

    标签: iphone objective-c core-data


    【解决方案1】:

    为什么你不能以对象的形式访问,所以为了这个 删除

    [fetchRequest setResultType:NSDictionaryResultType];
    

     [fetchRequest setPropertiesToFetch:[NSArray arrayWithObjects:@"first_property",@"second_property",nil]];
    

    那么现在

    table_dom = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
    

    table_dom 具有您的实体的对象,因此您在哪里使用此数组 提取对象并访问属性 first_property 和 second_property 只需使用 .运算符。

    【讨论】:

    • 我无法删除 setPropertiesToFetch 方法,因为它除了 setReturnsDistinctResults 之外还可以工作。查看 apple doc -> 如果是,则请求仅返回 propertiesToFetch 指定的字段的不同值。
    【解决方案2】:

    你是正确的,你会得到一个充满NSDictionaryNSArray。首先,我想指出您的代码中存在内存泄漏。 table_dom = [[NSArray alloc] init]; 不是必需的,因为 executeFetchRequest:error: 将返回 NSArray。因此,只需删除该行。

    拥有数组后,您可以执行以下操作:

    NSDictionary *dict = [table_dom objectAtIndex:indexPath.row];
    cell.textLabel.text = [dict objectForKey:@"first_property"];
    cell.detailTextLabel.text = [dict objectForKey:@"second_property"];
    

    【讨论】:

    • 感谢它运行良好,但我还添加了“self.table_dom”以使其 100% 运行,因为它曾经在我滚动 tableview 时崩溃(在 cellForRowAtIndexPath 方法中)
    • 是的,这可能是最简单的方法。否则,您也可以执行 [table_dom 保留]。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-10-25
    • 1970-01-01
    • 2016-04-13
    • 1970-01-01
    • 2013-08-16
    • 1970-01-01
    相关资源
    最近更新 更多