Core data 如何在Swift 3中访问NSFetchRequest结果?

Core data 如何在Swift 3中访问NSFetchRequest结果?,core-data,swift3,Core Data,Swift3,假设我想从核心数据中获取一些NSManagedObject,并列举所有结果: let request = NSFetchRequest<NSFetchRequestResult>() let entityDesc = NSEntityDescription.entity(forEntityName: "Chapter", in: context) request.entity = entityDesc do { let result = try context.execute

假设我想从核心数据中获取一些NSManagedObject,并列举所有结果:

let request = NSFetchRequest<NSFetchRequestResult>()
let entityDesc = NSEntityDescription.entity(forEntityName: "Chapter", in: context)
request.entity = entityDesc
do
{
    let result = try context.execute(request)
}
catch
{
    print("\(error)")
}
let request=NSFetchRequest()
让entityDesc=NSEntityDescription.entity(名为“Chapter”,in:context)
request.entity=entityDesc
做
{
let result=try context.execute(请求)
}
抓住
{
打印(“\(错误)”)
}
现在我有了一个NSPersistentStoreResult对象作为查询的结果,但我不知道如何处理它。类文档为空:


我应该如何检索提取请求返回的托管对象?

您使用
NSManagedObjectContext的
fetch
方法

首先创建提取请求,该请求可以是常规的,也可以是特定的:

let fetchRequest : NSFetchRequest<YourObject> = YourObject.fetchRequest

let fetchRequest : NSFetchRequest<NSFetchRequestResult> = YourObject.fetchRequest

根据我对
NSManagedObjectContext
标题的阅读,您从Swift调用的
execute()
方法用于只影响底层持久存储而不被上下文本身处理的请求。这对于fetch请求来说没有多大意义,因为它的唯一目的是将内容从持久存储带到上下文中

以下是核心数据中
NSManagedContext
头文件的相关片段:

您可以轻松获取:

假设你有照片实体

let request:NSFetchRequest<Photo> = Photo.fetchRequest()
/*        OR
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo")
 */
do {
    photos = try coreDataStack.context.fetch(request) as [Photo]
    collectionVIew.reloadData()
    print(photos?.count ?? "No Photo found")
} catch let error as NSError {
    print("Error in fetch :\(error)")
}
let-request:NSFetchRequest=Photo.fetchRequest()
/*或
let request=NSFetchRequest(entityName:“照片”)
*/
做{
photos=尝试coreDataStack.context.fetch(请求)为[Photo]
collectionVIew.reloadData()
打印(照片?.count??“未找到照片”)
}将let错误捕获为NSError{
打印(“获取时出错:\(错误)”)
}
// Method to pass a request to the store without affecting the contents of the managed object context.
// Will return an NSPersistentStoreResult which may contain additional information about the result of the action
// (ie a batch update result may contain the object IDs of the objects that were modified during the update).
// A request may succeed in some stores and fail in others. In this case, the error will contain information
// about each individual store failure.
// Will always reject NSSaveChangesRequests.
- (nullable __kindof NSPersistentStoreResult *)executeRequest:(NSPersistentStoreRequest*)request error:(NSError **)error API_AVAILABLE(macosx(10.10),ios(8.0));
let request:NSFetchRequest<Photo> = Photo.fetchRequest()
/*        OR
    let request = NSFetchRequest<NSFetchRequestResult>(entityName: "Photo")
 */
do {
    photos = try coreDataStack.context.fetch(request) as [Photo]
    collectionVIew.reloadData()
    print(photos?.count ?? "No Photo found")
} catch let error as NSError {
    print("Error in fetch :\(error)")
}