也许这个问题需要一些背景知识.
我一直在使用Core Data处理我的持久层,发现Core Data不是线程安全的,因此只需要NSManagedObjectContext限制在每个线程中.
所以我的方法是创建自定义后台线程NSManagedObjectContext,执行抓取,保存等,同时还创建主线程NSManagedObjectContext,用于NSManagedObject从获取中获取NSManagedObjectId并将其传递给调用方法.
默认情况下,Xcode的生成与核心数据模板的代码中使用lazy var的所有NSManagedObjectContext,NSManagedObjectModel等等.
所以我的问题是,是否
使用lazy var实例化方法进行创建NSManagedObjectContext,前提是lazy var为每个尝试访问的线程启动一个对象(不是线程安全的?)
要么
NSManagedObjectContext在每个线程中声明单独的变量,并使所有与线程相关的方法引用两个不同的方法,NSManagedObjectContext这些方法lazy var是线程安全的(?),并且在访问它时只创建一次,而不管线程如何.
先感谢您!
编辑:任何正在努力解决Core Data并发问题的人,本文列出了一个非常好的设计模式,正如Aaron在下面的评论中所指出的那样!
我认为惰性 var {}() 应该运行一次。但今天我遇到这个问题让我很困扰。我有任何想法。我哭了。
这是再现类:
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
private lazy var hotStockTableView: UITableView = {
let tableView = UITableView()
print("hotStockTableView ======> \(tableView) \n")
tableView.delegate = self
tableView.dataSource = self
// Here cause crash.
tableView.tableFooterView = UIView() // if comment this line, everthing is ok.
tableView.register(UITableViewCell.self, forCellReuseIdentifier: "cell")
return tableView
}()
override func viewDidLoad() {
super.viewDidLoad()
view.addSubview(hotStockTableView)
hotStockTableView.frame = view.bounds
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
print("tableView =====> \(tableView) \n")
if tableView == …Run Code Online (Sandbox Code Playgroud)