如何使用NSDictionary从NSArray中提取数据?

时间:2010-11-23 08:55:18

标签: iphone objective-c core-data

我尝试用核心数据制作一种“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检索对象吗?

由于

2 个答案:

答案 0 :(得分:2)

为什么不能以对象的形式访问,为此 除去

[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 通过简单地使用。操作

答案 1 :(得分:1)

您说明NSArray填充NSDictionary是正确的。首先,我想指出您的代码中存在内存泄漏。由于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"];