2015-04-04 54 views
0

今天下午我有一個奇怪的經歷,我不能把手指放在什麼問題上。我一直在使用Swift開發一款iPhone應用程序,並且我今天在路上試用了它。到目前爲止,我只在連接到Mac時對其進行了測試。iPhone墜毀時核心數據對象被刪除

該應用跟蹤位置並在用戶開車時將其保存到核心數據。一切都很好,數據正在保存。直到電話崩潰,核心數據似乎已經清空。數據絕對在電話崩潰之前保存,因爲我將保存的路線覆蓋在地圖視圖上,並且確實顯示。而且刪除數據的功能絕對不會被調用,因爲我沒有訪問調用它的唯一視圖控制器。

我的問題是,是否有其他人遇到過這種情況,或者是否存在一個已知問題,可以刪除核心數據,如果手機崩潰?

編輯:

這是我一直在使用保存代碼到核心數據:

var context = (UIApplication.sharedApplication().delegate as AppDelegate).managedObjectContext! 
     var savePosition = NSEntityDescription.insertNewObjectForEntityForName("Positions", inManagedObjectContext: context) as Positions 

     savePosition.poi = false 
     savePosition.time = currentTime 
     savePosition.direction = currentDirection 
     savePosition.latitude = currentLatitude 
     savePosition.longitude = currentLongitude 
     savePosition.game = currentGame 

     context.save(nil) 

我失蹤了一步?

+1

數據緩存,你可以使用它沒有問題。但是當你調用'saveContext()' – zisoft 2015-04-04 17:07:06

+0

時,它只能保存到持久數據存儲當你說保存你的意思是保存到我假設的持久存儲中,但是什麼類型的存儲?保存的數據在崩潰中丟失絕對不是正常的。我還沒有看到過。同意上面,聽起來像saveContext沒有發生。 – RegularExpression 2015-04-04 17:08:13

+0

我已經添加了我的代碼。我錯過了saveContext()嗎?我認爲我的context.save()正在完成這項工作? – 2015-04-04 17:10:35

回答

1

在AppDelegate中使用此功能可以捕獲錯誤並將其顯示在UIAlertController中。這可能有助於追蹤你的數據發生了什麼。

func saveContext() { 
    var error: NSError? = nil 

    if !managedObjectContext.hasChanges { 
     return 
    } 

    if managedObjectContext.save(&error) { 
     return 
    } 


    // Error occured 
    let alertController = UIAlertController(
     title: NSLocalizedString("Error", comment: ""), 
     message: "\(error?.localizedDescription)\n\(error?.userInfo)", 
     preferredStyle: .Alert 
    ) 

    let defaultAction = UIAlertAction(
     title: "Ok", 
     style: .Default, 
     handler: nil) 

    alertController.addAction(defaultAction) 

    self.navigationController?.topViewController.presentViewController(alertController, animated: true, completion: nil) 
} 
+0

Zisoft,太好了。感謝您的幫助。我已經添加了代碼,並且將會尋找問題。 – 2015-04-04 17:37:48

+0

祝你好運!並且不要忘記用'appDelegate.saveContext()';-)來替換'context.save(nil)'的所有出現 – zisoft 2015-04-04 17:39:51