在我的AppDelegate中,我的persistentStoreCoordinator
在选项中启用了NSMigratePersistentStoresAutomaticallyOption
和NSInferMappingModelAutomaticallyOption
:
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
// The persistent store coordinator for the application. This implementation creates and return a coordinator, having added the store for the application to it. This property is optional since there are legitimate error conditions that could cause the creation of the store to fail.
// Create the coordinator and store
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("knoData.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
let mOptions: NSDictionary = [NSMigratePersistentStoresAutomaticallyOption: true,
NSInferMappingModelAutomaticallyOption: true]
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: mOptions, error: &error) == nil {
coordinator = nil
// Report any error we got.
let dict = NSMutableDictionary()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error
error = NSError(domain: "YOUR_ERROR_DOMAIN", code: 9999, userInfo: dict)
// Replace this with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog("Unresolved error \(error), \(error!.userInfo)")
self.managedObjectContext?.reset()
abort()
}
当我升级我的核心数据版本时,它似乎工作没有崩溃,直到我用这段代码获取核心数据:
func fetchCoreData(){
var error : NSError?
let appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context : NSManagedObjectContext = appDel.managedObjectContext!
let fetchRequest = NSFetchRequest(entityName:"SavedData")
let fetchedResults = context.executeFetchRequest(fetchRequest, error: &error) as [data]?
if let resultsArray = fetchedResults {
if resultsArray.count > 0 {
var mostRecentData = resultsArray.count - 1
let newItem = resultsArray[mostRecentData] as data
NSLog("NEW ITEM \(newItem)")
clientID = newItem.userid
NSLog(clientID)
knoColor = Int(newItem.knoColor)
var upKNOs = newItem.upKNOs
var downKNOs = newItem.downKNOs
var upKNOString = upKNOs.stringByReplacingOccurrencesOfString("[", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
upKNOString = upKNOString.stringByReplacingOccurrencesOfString("]", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
upKNOString = upKNOString.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
upKNOString = upKNOString.stringByReplacingOccurrencesOfString(" ", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
upKNOArray = upKNOString.componentsSeparatedByString(",")
var downKNOString = downKNOs.stringByReplacingOccurrencesOfString("[", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
downKNOString = downKNOString.stringByReplacingOccurrencesOfString("]", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
downKNOString = downKNOString.stringByReplacingOccurrencesOfString("\"", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
downKNOString = downKNOString.stringByReplacingOccurrencesOfString(" ", withString: "", options: NSStringCompareOptions.LiteralSearch, range: nil)
downKNOArray = downKNOString.componentsSeparatedByString(",")
var index = find(upKNOArray, "")
if(index != nil){
upKNOArray.removeAtIndex(index!)
}
var index2 = find(downKNOArray, "")
if(index2 != nil){
downKNOArray.removeAtIndex(index2!)
}
censor = newItem.censor
unit = newItem.distUnit
radius = newItem.radius
slideAnimation = newItem.slideAnimation
handle = newItem.handle
NSLog("Censor(\(censor)) was set to newItem.censor(\(newItem.censor))")
} else {
NSLog("No results from fetch request.")
var request = HTTPTask()
request.GET(API, parameters: nil, success: {(response: HTTPResponse) in
if response.responseObject != nil {
let data = response.responseObject as NSData
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
self.setFirstCoreData(str!)
}
},failure: {(error: NSError, response: HTTPResponse?) in
NSLog("error: \(error)")
})
}
}
}
func setFirstCoreData(id: String){
//NSLog(device)
//NSLog("\(screenWidth)")
let appDel : AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate
let context : NSManagedObjectContext = appDel.managedObjectContext!
let entity = NSEntityDescription.entityForName( "SavedData", inManagedObjectContext: context )
var newItem = data( entity: entity!, insertIntoManagedObjectContext: context )
var error : NSError?
newItem.userid = id
clientID = id
newItem.upKNOs = "[]"
newItem.downKNOs = "[]"
knoColor = Int(arc4random_uniform(UInt32(colors.count)))
newItem.knoColor = Int32(knoColor!)
newItem.censor = false
newItem.distUnit = Int32(0)
newItem.radius = Double(2.5)
newItem.slideAnimation = true
newItem.handle = handle
unit = newItem.distUnit
radius = newItem.radius
slideAnimation = newItem.slideAnimation
if !context.save(&error) {
NSLog("Unresolved error \(error), \(error!.userInfo)")
}
NSLog("CoreData(newItem):\(newItem)")
NSLog("CoreData(newItem.description):\(newItem.description)")
}
代码没有问题,因为它在我更新核心数据模型之前一直有效,我最终在这里得到了一个EXC_BAD_ACCESS错误:
我认为我的问题是我尝试访问的属性没有初始值,但我不确定解决方案,因为我之前从未使用过Core Data Migrations。