Fetching selected attribute in entities

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-27 14:55:21

There are two possibilities: You can issue a normal fetch request and extract an array containing the wanted attribute from the result, using map():

let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]

var error : NSError?
if let result = context.executeFetchRequest(fetchReq, error: &error) as? [Model] {
    let friendIDs = map(result) { $0.friendID }
    println(friendIDs)
} else {
    println("fetch failed: \(error!.localizedDescription)")
}

Swift 2:

let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]

do {
    let result = try context.executeFetchRequest(fetchReq) as! [Model]
    let friendIDs = result.map { $0.friendID }
    print(friendIDs)
} catch let error as NSError {
    print("fetch failed: \(error.localizedDescription)")
}

Or you set the resultType to .DictionaryResultType and propertiesToFetch to the wanted attribute. In this case the fetch request will return an array of dictionaries:

let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]
fetchReq.propertiesToFetch = ["friendID"]
fetchReq.resultType = .DictionaryResultType

var error : NSError?
if let result = context.executeFetchRequest(fetchReq, error: &error) as? [NSDictionary] {
    let friendIDs = map(result) { $0["friendID"] as String }
    println(friendIDs)
} else {
    println("fetch failed: \(error!.localizedDescription)")
}

Swift 2:

let fetchReq = NSFetchRequest(entityName: "Identities")
fetchReq.sortDescriptors = [sortDesc]
fetchReq.propertiesToFetch = ["friendID"]
fetchReq.resultType = .DictionaryResultType

do {
    let result = try context.executeFetchRequest(fetchReq) as! [NSDictionary]
    let friendIDs = result.map { $0["friendID"] as! String }
    print(friendIDs)
} catch let error as NSError {
    print("fetch failed: \(error.localizedDescription)")
}

The second method has the advantage that only the specified properties are fetched from the database, not the entire managed objects.

It has the disadvantage that the result does not include pending unsaved changes in the managed object context (includesPendingChanges: is implicitly set to false when using .DictionaryResultType).

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!