因此,在查看Core Data Snippets时,我发现了以下代码:
...
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctValues:YES];
[request setPropertiesToFetch:[NSArray arrayWithObject:@"<#Attribute name#>"]];
// Execute the fetch
NSError *error;
id requestedValue = nil; // WTF? This isn't defined or used anywhere
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
// handle the error
}
Run Code Online (Sandbox Code Playgroud)
这很棒,对于我需要的东西来说似乎很完美......但是如何实际使用它呢?我假设因为它返回字典,我需要一个键来获取值 - 但是键定义了哪里?这是"id requestedValue = nil"行吗?如果是这样,"requestedValue"如何成为关键?Xcode在"requestedValue"声明中给出了一个关于未使用变量的编译器警告.我觉得我在这里错过了一些东西.
提前感谢您提供的任何帮助.
Jas*_*oco 28
requestedValue什么都不是,显然没有被使用(也许它是其他一些例子的一部分,它被剪切并粘贴到这个示例代码中 - 谁知道).你可以忽略它.
字典的键与您提取的属性相同,并在模型中定义.因此,例如,如果您有一个定义了三个属性的person实体,name,age,phoneNumber,并且您只请求了name,那么这将是您词典中唯一包含数据的键.所以:
[request setEntity:entity];
[request setResultType:NSDictionaryResultType];
[request setReturnsDistinctResults:YES];
[request setPropertiesToFetch:[NSArray arrayWithObject:@"name"]];
// Execute the fetch
NSError *error;
NSArray *objects = [managedObjectContext executeFetchRequest:request error:&error];
if (objects == nil) {
abort();
}
for( NSDictionary* obj in objects ) {
NSLog(@"Person: %@", [obj objectForKey:@"name"]);
}
// ...
Run Code Online (Sandbox Code Playgroud)
因此,如果您的数据存储中有5个人名为Bob,Sally,Joe,Freida和Sue,您会看到这些名称打印出来.如果要使用任何其他属性(如年龄),则必须将其添加到您设置的数组中setPropertiesToFetch:.
但是,在大多数情况下,最好只是检索托管对象.该对象将出现故障,因此除非您实际访问它们,否则您甚至不会将属性带入内存.另外,如果要对对象进行更改,可以将它们持久保存到商店(使用托管对象).
| 归档时间: |
|
| 查看次数: |
15668 次 |
| 最近记录: |