我是 iOS 核心数据的新手,我有大约 5000 strip 有多个键值的记录。 我想将其保存在 backgorund 的核心数据存储中,这样应用程序就不会卡住。我已经保存了它,代码是在 Appdelegate.swift 类中实现的,但是当应用程序运行时,它会卡住,直到从 API 加载数据并将其保存到核心数据存储中。
这是我的代码:-
let tempArray = NSMutableArray(array : data!)
for i in 0 ..< tempArray.count {
print(i)
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {
return
}
if #available(iOS 10.0, *) {
self.moc = appDelegate.persistentContainer.viewContext
}
let entity = NSEntityDescription.insertNewObject(forEntityName: "Product", into: self.moc!) as! Product
if (tempArray.object(at: i) as! NSDictionary).value(forKey: "id") != nil {
entity.setValue((tempArray.object(at: i) as! NSDictionary).value(forKey: "id") as! NSNumber , forKey: "id")
}
DispatchQueue.main.async {
do {
try self.moc?.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
我尝试使用 try self.moc?.save() 来放入调度异步,但它给出了错误
最佳答案
你可以使用OperationQueue来做到这一点
let op = OperationQueue()
op.addOperation {
//Your task goes here
do {
try self.moc.save()
}
catch {
fatalError("Failure to save context: \(error)")
}
}
方法2
DispatchQueue.main.async {
do {
self.moc.save()
} catch let error as NSError {
print("Could not save. \(error), \(error.userInfo)")
}
}
这样做
moc.perform {
if let a = (tempArray.object(at: i) as! NSDictionary).value(forKey: "id") {
let obj = NSManagedObject(entity: entity, insertInto: moc)
obj.setValue(a as! NSNumber , forKey: "id")
}
}
DispatchQueue.main.async {
do {
try self.moc.save()
} catch {
fatalError("Failure to save context: \(error)")
}
}
关于ios - 应用程序卡住直到将数据保存到核心数据中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41980371/