Fetching selected attribute in entities
我有一个具有多个属性的核心数据实体,我想要一个属性中所有对象的列表。我的代码如下所示:
1
2 3 4 5 6 7 8 9 10 11 12 |
let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context:NSManagedObjectContext = appDel.managedObjectContext! let sortDesc = NSSortDescriptor(key:”username”, ascending: true) let fetchReq = NSFetchRequest(entityName:”Identities”) let en = NSEntityDescription.entityForName(“Identities”, inManagedObjectContext: context) userList = context.executeFetchRequest(fetchReq, error: nil) as [Usernames] |
但这给了我一个 NSException 错误,我不知道为什么,或者我应该怎么做。我已经阅读了 NSFetchRequest 类的描述,但无法理解它。
任何建议都将不胜感激。
编辑:收到 Bluehound 的提示后,我将代码更改为:
1
2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 |
var userList = [Model]()
@IBAction func printUsers(sender: AnyObject) { let appDel:AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate let context:NSManagedObjectContext = appDel.managedObjectContext! let sortDesc = NSSortDescriptor(key:”friendID”, ascending: true) let fetchReq = NSFetchRequest(entityName:”Identities”) let en = NSEntityDescription.entityForName(“Identities”, inManagedObjectContext: context) userList = context.executeFetchRequest(fetchReq, error: nil) as [Model] println(userList) } |
运行时错误消失了,但我仍然不知道它是否有效,因为我不确定如何将列表转换为字符串列表。
一如既往,我们将不胜感激。
- 使用 NSFetchRequest\\ 的 propertiesToFetch 属性而不是 valueForKey
- @Bluehound 你能告诉我吗,我在初始化 NSPropertyDescription 时遇到了麻烦。
- println(userList) 的输出是什么样的?
- @pbasdf [ , , ] 与我获取整个班级时相同。
- 行。尝试添加 fetchReq.resultType = .DictionaryResultType。
- @pbasdf 这在 println 函数中给我一个错误,说 NSArray 元素无法匹配 Swift Array 元素类型。
- 哦,对不起,将 as [Model] 更改为 as [AnyObject]。
有两种可能:可以发出正常的fetch请求
并从结果中提取包含所需属性的数组,
使用 map():
1
2 3 4 5 6 7 8 9 10 |
let fetchReq = NSFetchRequest(entityName:”Identities”)
fetchReq.sortDescriptors = [sortDesc] var error : NSError? |
斯威夫特 2:
1
2 3 4 5 6 7 8 9 10 |
let fetchReq = NSFetchRequest(entityName:”Identities”)
fetchReq.sortDescriptors = [sortDesc] do { |
或者您将 resultType 设置为 .DictionaryResultType
和 propertiesToFetch 到想要的属性。
在这种情况下,获取请求将返回一个字典数组:
1
2 3 4 5 6 7 8 9 10 11 12 |
let fetchReq = NSFetchRequest(entityName:”Identities”)
fetchReq.sortDescriptors = [sortDesc] fetchReq.propertiesToFetch = [“friendID”] fetchReq.resultType = .DictionaryResultType var error : NSError? |
斯威夫特 2:
1
2 3 4 5 6 7 8 9 10 11 12 |
let fetchReq = NSFetchRequest(entityName:”Identities”)
fetchReq.sortDescriptors = [sortDesc] fetchReq.propertiesToFetch = [“friendID”] fetchReq.resultType = .DictionaryResultType do { |
第二种方法的优点是只有指定的属性
从数据库中获取,而不是从整个托管对象中获取。
它的缺点是结果不包含pending
托管对象上下文中未保存的更改(includesPendingChanges:
使用 .DictionaryResultType 时隐式设置为 false).
- 我从您问题中的代码中获取了实体名称”Identities”和托管对象子类的名称”Model”。通常人们会为两者使用相同的名称。
- 再次感谢 Martin,您永远不会失望 :) 是的,我知道名称不是最佳的,它只是我很久以前创建的”测试项目”。
来源:https://www.codenong.com/28054621/