ios - 应用程序卡住直到将数据保存到核心数据中

标签 ios iphone swift database core-data

我是 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/

相关文章:

ios - Swift 中的 Int 到 UInt(反之亦然)位转换

ios - UI 测试在 Xcode 机器人运行时将文本键入 TextView 时失败

iphone - 可以在不越狱的情况下将 iPhone/iPad 屏幕镜像到显示器上吗?

iphone - 对应用程序首选项的更改未保存或无法立即可用?

iphone - 我的 UIWebView 正在延迟重新加载。当我想要显示数据时,如何使其重新加载/刷新?

ios - PubNub 显示打字指示器

swift - 如何在 0.3 秒后执行给定次数的 Action ?

android - 未找到 j2objc 命令

ios - 拉取刷新插件: PullToBounce Wrapper UIScrollView

ios - 查找函数是否已完成循环 firebase