Swift 2.0 Migration errors

ε祈祈猫儿з 提交于 2019-12-19 09:03:13

问题


I've watched the WWDC sessions, reading the new programmers book on Swift, and reading all the related questions on Stack Overflow I could find. I fixed most errors in my app after migrating from Swift 1.2 to Swift 2.0.

However there's still a few that I've not managed to solve.

Downcasting AnyObject

Error:

Cannot downcast from '[AnyObject]' to a more optional type '[NSManagedObject]'

Code:

    let fetchRequest = NSFetchRequest(entityName: formulaEntity)

    var error: NSError?

    do {
        let fetchedResults = try managedContext.executeFetchRequest(fetchRequest) as! [NSManagedObject]?

        if let results = fetchedResults {
            stocks = results
        } else {
            print("Could not fetch \(error), \(error!.userInfo)")
        }
    } catch {
        print("ERROR: \(error)")
    }

The error shown is happening in the let fetchedResults = try... line

Another strange error I'm having is in my AppDelegate:

Error:

'NSMutableDictionary' is not convertible to '[NSObject : AnyObject]'

Code:

    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("Stocks.sqlite")
    var error: NSError? = nil
    var failureReason = "There was an error creating or loading the application's saved data."
    do {
        try coordinator!.addPersistentStoreWithType(NSSQLiteStoreType, configuration: nil, URL: url, options: nil)
    } catch var error1 as NSError {
        error = error1
        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 as [NSObject : AnyObject])
        // 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)")
        abort()
    } catch {
        fatalError()
    }

    return coordinator
}()

I have not ever touched the code above. So I have no idea why this wasn't migrated properly, by Apple's Migration tool.

Another error in my AppDelegate:

Binary operator '&&' cannot be applied to two Bool operands

Call can throw, but it is not marked with 'try' and the error is not handled.

Code:

func saveContext () {
    if let moc = self.managedObjectContext {
        var error: NSError? = nil
        if moc.hasChanges && !moc.save() {
            // 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.
            NSLog("Unresolved error \(error), \(error!.userInfo)")
            abort()
        }
    }
}

Again I havn't touched this part of AppDelegate, and not sure what exactly is wrong with the code above.


回答1:


Cannot downcast from '[AnyObject]' to a more optional type '[NSManagedObject]'

In Swift 1.2, executeFetchRequest(:_) returned [AnyObject]?. In Swift 2, it returns [AnyObject] because the new try… syntax returns a non-optional.

(In the case that the method would return nil, the method would not return at all, and control would move to the catch block.)


'NSMutableDictionary' is not convertible to '[NSObject : AnyObject]'

This means you're trying to insert something into an NSMutableDictionary that can't be converted to an Objective-C object. In your case, I think it's because error is a struct conforming to ErrorType, rather than an NSError object. Try adding error1 instead.


Call can throw, but it is not marked with 'try' and the error is not handled.

save() might throw an error so it needs to be executed with try, instead of being evaluated as a bool. As Martin R. points out in the comments, the answer to this question provides a complete solution so I won't rehash it here.




回答2:


It seems there is a severe Swift 2 migration problem for CoreData on AppDelegate. I was able to fix the problem by completely replacing the AppDelegate CoreData Swift 1.2 to Swift 2.0.

What you need to do is delete the following

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {

lazy var managedObjectContext: NSManagedObjectContext = {

// MARK: - Core Data Saving support

func saveContext ()

And pasting the Swift 2.0 code:

lazy var persistentStoreCoordinator: NSPersistentStoreCoordinator = {
    // The persistent store coordinator for the application. This implementation creates and returns 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
    let coordinator = NSPersistentStoreCoordinator(managedObjectModel: self.managedObjectModel)
    let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent("SingleViewCoreData.sqlite")
    var failureReason = "There was an error creating or loading the application's saved data."
    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.
        NSLog("Unresolved error \(wrappedError), \(wrappedError.userInfo)")
        abort()
    }

    return coordinator
}()

lazy var managedObjectContext: NSManagedObjectContext = {
    // Returns the managed object context for the application (which is already bound to the persistent store coordinator for the application.) This property is optional since there are legitimate error conditions that could cause the creation of the context to fail.
    let coordinator = self.persistentStoreCoordinator
    var managedObjectContext = NSManagedObjectContext(concurrencyType: .MainQueueConcurrencyType)
    managedObjectContext.persistentStoreCoordinator = coordinator
    return managedObjectContext
}()

// MARK: - Core Data Saving support

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
            NSLog("Unresolved error \(nserror), \(nserror.userInfo)")
            abort()
         }
     }
 }
}

This should fix the problem.



来源:https://stackoverflow.com/questions/30823072/swift-2-0-migration-errors

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!