- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
似乎有两种方法可以在不阻塞主线程 UI 的情况下在 CoreData 中执行异步读取。
来源:https://www.advancedswift.com/core-data-background-fetch-save-create/
// Create a new background managed object context
let context = persistentContainer.newBackgroundContext()
// If needed, ensure the background context stays
// up to date with changes from the parent
context.automaticallyMergesChangesFromParent = true
// Perform operations on the background context
// asynchronously
context.perform {
do {
// Create a fetch request
let fetchRequest: NSFetchRequest<CustomEntity>
fetchRequest = CustomEntity.fetchRequest()
fetchRequest.fetchLimit = 1
let objects = try context.fetch(fetchRequest)
// Handle fetched objects
}
catch let error {
// Handle error
}
}
来源:https://www.marcosantadev.com/coredata_crud_concurrency_swift_2/
let privateManagedObjectContext = persistentContainer.newBackgroundContext()
// Creates a fetch request to get all the dogs saved
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Dog")
// Creates `asynchronousFetchRequest` with the fetch request and the completion closure
let asynchronousFetchRequest = NSAsynchronousFetchRequest(fetchRequest: fetchRequest) { asynchronousFetchResult in
// Retrieves an array of dogs from the fetch result `finalResult`
guard let result = asynchronousFetchResult.finalResult as? [Dog] else { return }
// Dispatches to use the data in the main queue
DispatchQueue.main.async {
// Do something
}
}
do {
// Executes `asynchronousFetchRequest`
try privateManagedObjectContext.execute(asynchronousFetchRequest)
} catch let error {
print("NSAsynchronousFetchRequest error: \(error)")
}
但是,请注意,如果我要启用标志 -com.apple.CoreData.ConcurrencyDebug 1
,上面的代码将不幸地导致 fatal error 。到目前为止,我还没有很好的解决方案。更多详情请引用Why I am getting Multithreading_Violation_AllThatIsLeftToUsIsHonor for this simplest NSAsynchronousFetchRequest use case?
请问newBackgroundContext + NSFetchRequest
和 newBackgroundContext + NSAsynchronousFetchRequest
有什么区别?
我应该如何选择一个而不是另一个?谢谢。
最佳答案
<强>1。关于 __Multithreading_Violation_AllThatIsLeftToUsIsHonor__
异常:
本帖有详细讨论:
CoreData asynchronous fetch causes concurrency debugger error
一致认为这是 CoreData 中的一个错误。
有错误报告:https://openradar.appspot.com/30692722在撰写本文时 8 年后仍然开放。
<强>2。如何正确使用NSAsynchronousFetchRequest
该 API 于 2014 年推出,并在此 WWDC 视频中进行了讨论 225_sd_whats_new_in_core_data .
没有提到 NSAsynchronousFetchRequest
应该在主( View )上下文还是后台上下文中使用。
我在 GitHub 上使用 NSAsynchronousFetchRequest
查看了几个随机实现,并找到了主要和后台上下文的示例。
然而,在使用后台上下文时,您必须做的一件事是将获取执行包装在perform
block ( documentation ) 中。
在您链接的文章和上面摘录的示例中,缺少此内容!
它应该是这样的:
privateManagedObjectContext.perform {
do {
try privateManagedObjectContext.execute(asynchronousFetchRequest)
} catch let error {
print("error trying to fetch saving objects:", error.localizedDescription)
}
}
同一篇文章还有另一个潜在的问题,所以要持保留态度:
DispatchQueue.main.async {
// here the objects in result (belongs to private context) are
// accessed on the main queue – the whole point is to *not* do that!
// one might get away with it because it is only read access to id
// but good luck debugging this...
let dogs: [Dog] = result.lazy
.flatMap { $0.objectID }
.flatMap { mainManagedObjectContext.object(with: $0) as? Dog }
// ...
我对NSAsynchronousFetchRequest
的理解是,它最好从主上下文中使用,它的目的实际上是对你隐藏后台上下文业务。
所以:mainContext + NSAsynchronousFetchRequest
<强>3。我应该如何取舍?
在我看来,创建NSAsynchronousFetchRequest
的初衷是为了简化我们的异步核心数据获取。为此,您可以充分利用它来发挥自己的优势,尤其是当您需要处理进度和取消时。
但是我可能不会在我的项目中使用它,因为
最后一个想法 - 在开始异步获取之前,请确保您确实需要它。最好先优化查询、数据模型或批处理设置的性能。
关于ios - CoreData 中的异步读取 - 使用 newBackgroundContext + FetchRequest 与 newBackgroundContext + NSAsynchronousFetchRequest 的区别?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70544438/
Xcode beta 5 推出 @FetchRequest对于 SwiftUI。 我有一个 View ,它有一个 @FetchRequest . NSFetchRequest是在管理器中创建的,该管理
带有实体 Node 的核心数据模型有 name , createdAt , 多对多关系 children和一对一的关系parent (都是可选的)。使用 CodeGen 类定义。 使用 @FetchR
我试图将我的@fetchrequest属性移到辅助类,而不是View,但是每次尝试这样做时,都会收到一条错误的指令错误。 谁能帮我? 这是我的代码的示例: ViewModel: class ViewM
我的 SwiftUI 项目中有以下代码 @FetchRequest private var step: FetchedResults private var processID: UUID priva
我有一个使用 @FetchRequest 显示来自 CoreData 的对象的列表,我想为用户提供一个栏按钮,单击该按钮将过滤显示的列表。如何更改 @FetchRequest 谓词并动态重新运行它以使
我的 SwiftUI 项目中有以下代码 @FetchRequest private var step: FetchedResults private var processID: UUID priva
当我向 CoreData 的一个实体插入数据时,所有行均已成功插入(已保存)。 但是当我尝试使用 FetchRequest 获取数据时,即使插入的行数为 3 或 4 或任何值(超过 1),也只会收到一
更新以下问题:我们能够通过父子关系使用父实体获取请求来查询子实体。示例查询如下: NSPredicate *myPredicate = [NSPredicate predicateWithForm
我正在尝试从我的数据库中获取请求。但我的回应为零。获取是可以的,因为当我使用这种方法时,我得到“有时”值。 (我知道我在数据库中有数据)。我认为这在某种程度上与线程问题有关,或者因为我正在使用多上下文
如何按土耳其语对 fetchResult 进行排序,土耳其语字符在结果末尾排序。 let managedObjectContext = (UIApplication.shared.delegate a
我有一个扩展 NSManagedObject 的静态函数得到这样的对象...... NSManagedObject.get(type: MYUser.self, with: ("id", "SomeU
使用方法 @FetchRequest为了检索单个对象而不是 FetchedResults ?在我看来,我只需要一个对象。是否有另一种方法来执行查询并根据唯一的属性值(例如 ID)获取单个对象? str
我有一组数据,其中一个属性(固件)是一对多关系。 如果我想获取固件 id 为 1 的任何记录,我可以使用创建谓词 @"(ANY Firmware.FID==1)" 然后我有另一组条件,可以使用进一步细
在我的应用程序中,我有两个 CoreData 实体,它们的关系是一对多的:人物 -> 主题 我正在使用列表呈现人们的名字 struct PeopleListView: View { @Fetc
我有 2 个实体: 出席: import Foundation import CoreData extension Attendance { @NSManaged var date: NSDa
更新说明:我正在使用 Big Nerd Ranch CoreDataStack如果你们想知道的话。 我已经为这个具体问题苦苦挣扎了一段时间了。基本上我试图从 CNContactStore 获取联系人并
我正在尝试找到一种方法来预测给定日期第一次发生的事件。假设一个事件在一天中发生多次(范围 1-16),我只希望它返回第一次出现的事件,然后在第二天查找下一个第一次出现的事件。 最佳答案 您无法通过一个
所以我有两个实体。列表和评论。一个列表可以有多个关联的评论。 extension Listing { @NSManaged var listingTitle: String? @NSM
我在尝试过滤 fetchRequest 时脑子崩溃了。 我能够获取实体每条记录的完整详细信息,但我只想要当前 indexPath 处记录的详细信息。 这是我的代码目前所在的位置: -(void) fe
我正在尝试获取按其属性之一(单词)过滤的实体列表,为此我使用了 fetchedResultsController,一切看起来都正常。该列表已加载并显示在我的 tableView 上,我什至可以对列表进
我是一名优秀的程序员,十分优秀!