我试图在自定义类中声明两个属性作为选项 - String和Int.
我在MyClass中这样做:
var myString: String?
var myInt: Int?
Run Code Online (Sandbox Code Playgroud)
我可以解释它们如下:
required init?(coder aDecoder: NSCoder) {
myString = aDecoder.decodeObjectForKey("MyString") as? String
myInt = aDecoder.decodeIntegerForKey("MyInt")
}
Run Code Online (Sandbox Code Playgroud)
但是对它们进行编码会在Int行上产生错误:
func encodeWithCoder(aCoder: NSCoder) {
aCoder.encodeInteger(myInt, forKey: "MyInt")
aCoder.encodeObject(myString, forKey: "MyString")
}
Run Code Online (Sandbox Code Playgroud)
当XCode提示我打开Int时,错误只会消失,如下所示:
aCoder.encodeInteger(myInt!, forKey: "MyInt")
Run Code Online (Sandbox Code Playgroud)
但这显然会导致崩溃.所以我的问题是,如何将Int作为一个可选项来对待,就像String一样?我错过了什么?
我有一个应用程序需要大约一分钟的时间来设置,所以当用户点击“开始新游戏”时,我想在数据加载到核心数据时显示一个活动微调器。
我知道我必须在后台线程上执行此操作,以便我可以在主线程上更新 UI,但我不知道如何在后台线程中保存托管上下文。这是我到目前为止所拥有的:
func startNewGame() {
initiateProgressIndicator() // start the spinner and 'please wait' message
DispatchQueue.global(qos: .background).async {
self.coreDataStack.importDefaultData() // set up the database for the new game
DispatchQueue.main.async {
stopProgressIndicator()
// Transition to the next screen
let vc: IntroViewController = self.storyboard?.instantiateViewController(withIdentifier: "IntroScreen") as! IntroViewController
vc.rootVCReference = self
vc.coreDataStack = self.coreDataStack
self.present(vc, animated:true, completion:nil)
}
}
Run Code Online (Sandbox Code Playgroud)
在 importDefaultData() 中,我需要多次保存,但是当我尝试这样做时它会崩溃。我现在明白这是因为我试图从后台线程访问主上下文。下面是函数的基本结构:
func importDefaultData() {
// import data into Core Data here, code not shown for brevity
saveContext()
// import more data into …Run Code Online (Sandbox Code Playgroud)