当我创建一个新项目时生成的 AppDelegate xcode 中有错误,我正在努力调试,因为我是 swift 的新手。为什么生成的文件会返回错误?在创建新的 swift 项目时如何防止这种情况?
错误 1
lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator? = {
var coordinator: NSPersistentStoreCoordinator? = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("Swift_Conversion.sqlite")
var error: NSError? = nil
var failureReason = "There was an error creating or loading the application's saved data."
if coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil, error: &error) == nil {
coordinator = nil
//ERROR: EXTRA ARGUMENT 'ERROR' IN CALL
var dict = [String: AnyObject]()
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)
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
return coordinator
}()
错误 2
func saveContext () {
if let moc = self.managedObjectContext {
var error: NSError? = nil
if moc.hasChanges && !moc.save(&error) {
//ERROR: CANNOT CONVERT VALUE OF TYPE 'INOUT NSERROR?'(AKA 'INOUT OPTIONAL<NSERROR>') TO EXPECTED ARGUMENT TYPE '()'
NSLog("Unresolved error \(error), \(error!.userInfo)")
abort()
}
}
}
我曾尝试手动调试它,但我在编辑 AppDelegate 和使用 swift 方面的经验不足让我失望,因为我删除的每个错误都伴随着一些新错误。
最佳答案
addPersistentStoreWithType
的方法签名已更改。它现在是 throwable
并且必须像这样使用:
do {
try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
} catch {
// Report any error we got.
var dict = [String: AnyObject]()
dict[NSLocalizedDescriptionKey] = "Failed to initialize the application's saved data"
dict[NSLocalizedFailureReasonErrorKey] = failureReason
dict[NSUnderlyingErrorKey] = error as NSError
let wrappedError = 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.
print("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
abort()
}
与 NSManagedObjectContext
上的 save
方法相同:
func saveContext () {
if managedObjectContext!.hasChanges {
do {
try managedObjectContext!.save()
} catch {
// Replace this implementation 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.
let nserror = error as NSError
print("Unresolved error \(nserror), \(nserror.userInfo)")
abort()
}
}
}
关于ios - 为什么生成的 AppDelegate 文件有错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33105760/