将iOS Core数据添加到现有项目 - 在解包可选值时出错 [英] Add iOS Core Data to an existing project - error while unwrapping an optional Value

查看:105
本文介绍了将iOS Core数据添加到现有项目 - 在解包可选值时出错的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图将CoreData添加到现有项目。所以,我从一个新的项目复制数据模型(SWS.xcdatamodel)和AppDelegate文件。然后我在AppDelegate方法中更改了项目名称和数据模型名称

  import UIKit 
import CoreData

@UIApplicationMain
class AppDelegate:UIResponder,UIApplicationDelegate {

var window:UIWindow?


func应用程序(应用程序:UIApplication,didFinishLaunchingWithOptions launchOptions:[NSObject:AnyObject]?) - > Bool {
//应用程序启动后覆盖自定义点。
return true
}

func applicationWillResignActive(application:UIApplication){
//当应用程序将从活动状态转换为非活动状态时发送。这可能发生在某些类型的临时中断(例如来电或SMS消息)时,或者当用户退出应用程序并且开始转换到后台状态时。
//使用此方法暂停正在进行的任务,禁用计时器,并降低OpenGL ES帧速率。游戏应该使用这种方法暂停游戏。
}

func applicationDidEnterBackground(application:UIApplication){
//使用此方法释放共享资源,保存用户数据,使计时器无效并存储足够的应用程序状态信息您的应用程序到其当前状态,以防它以后终止。
//如果您的应用程序支持后台执行,则调用此方法,而不是applicationWillTerminate:当用户退出时。
}

func applicationWillEnterForeground(application:UIApplication){
//调用作为从后台到非活动状态的转换的一部分;在这里你可以撤消许多在输入背景所做的更改。
}

func applicationDidBecomeActive(application:UIApplication){
//在应用程序处于非活动状态时,重新启动已暂停(或尚未启动)的任务。如果应用程序先前在后台,则可选择刷新用户界面。
}

func applicationWillTerminate(application:UIApplication){
//当应用程序即将终止时调用。如果适当,保存数据。另请参见applicationDidEnterBackground :.
}

// MARK: - 核心数据堆栈

lazy var applicationDocumentsDirectory:NSURL = {
//应用程序用于存储核心数据存储文件。此代码在应用程序的文档应用程序支持目录中使用名为at.meinhard-kissich.SWSCore的目录。
let urls = NSFileManager.defaultManager()。URLsForDirectory(.DocumentDirectory,inDomains:.UserDomainMask)
return urls [urls.count-1]
}()
$ b b lazy var managedObjectModel:NSManagedObjectModel = {
//应用程序的管理对象模型。此属性不是可选的。这是一个致命的错误,应用程序无法找到和加载其模型。
let modelURL = NSBundle.mainBundle()。URLForResource(SWS,withExtension:momd)!
return NSManagedObjectModel(contentsOfURL:modelURL)!
}()

lazy var persistentStoreCoordinator:NSPersistentStoreCoordinator = {
//应用程序的持久存储协调器。此实现创建并返回一个协调器,并向其添加了应用程序的存储。此属性是可选的,因为存在可能导致存储创建失败的合法错误条件。
//创建协调器和存储
let coordinator = NSPersistentStoreCoordinator(managedObjectModel:self.managedObjectModel)
let url = self.applicationDocumentsDirectory.URLByAppendingPathComponent(SWS.sqlite)
var failureReason =创建或加载应用程序保存的数据时出错。
do {
try coordinator.addPersistentStoreWithType(NSSQLiteStoreType,configuration:nil,URL:url,options:nil)
} catch {
//报告我们得到的任何错误。
var dict = [String:AnyObject]()
dict [NSLocalizedDescriptionKey] =无法初始化应用程序保存的数据
dict [NSLocalizedFailureReasonErrorKey] = failureReason

dict [NSUnderlyingErrorKey] = error as NSError
let wrappedError = NSError(domain:YOUR_ERROR_DOMAIN,代码:9999,userInfo:dict)
//用代码替换以正确处理错误。
// abort()导致应用程序生成崩溃日志并终止。您不应在运送应用程序中使用此功能,但在开发过程中可能很有用。
NSLog(Unresolved error \(wrappedError),\(wrappedError.userInfo))
abort()
}

return coordinator
}()

lazy var managedObjectContext:NSManagedObjectContext = {
//返回应用程序的管理对象上下文(已经绑定到应用程序的持久存储协调器)此属性可选,因为有可能导致上下文创建失败的合法错误条件。
let coordinator = self.persistentStoreCoordinator
var managedObjectContext = NSManagedObjectContext(concurrencyType:.MainQueueConcurrencyType)
managedObjectContext.persistentStoreCoordinator = coordinator
return managedObjectContext
}()

// MARK: - 核心数据保存支持

func saveContext(){
如果managedObjectContext.hasChanges {
do {
try managedObjectContext.save )
} catch {
//用代码替换此实现,以正确处理错误。
// abort()导致应用程序生成崩溃日志并终止。您不应在运送应用程序中使用此功能,但在开发过程中可能很有用。
let nserror = error as NSError
NSLog(未解决的错误\(nserror),\(nserror.userInfo))
abort()
}
}
}



}

之后,我试图写一个新的数据集到数据库

  let appDelegate =(UIApplication.sharedApplication !AppDelegate)
let managedContext = appDelegate.managedObjectContext

let entity =(NSEntityDescription.insertNewObjectForEntityForName(WeatherData,inManagedObjectContext:managedContext))as NSManagedObject


entity.setValue(32,forKey:id)


do {
try managedContext.save()
} catch let错误为NSError {
print(Could not save \(error),\(error.userInfo))
}
print(obj saved)



不幸的是,我总是得到以下错误:

 致命错误:意外找到nil同时展开可选值

在此行中:

  let modelURL = NSBundle.mainBundle()。URLForResource(SWS,withExtension:momd)! 

问题在哪里?




  • 谢谢!


解决方案


在哪里可能是问题?


很简单:你强制解开 NSBundle .mainBundle()。URLForResource(SWS,withExtension:momd),意味着如果值不存在应用程序将崩溃。确实这里的问题是NSBundle找不到你的资源。


I'm trying to add CoreData to an existing project. So, I copied the data model (SWS.xcdatamodel) and the AppDelegate file from a new project. Then I changed the project name and data model name in the AppDelegate methods

import UIKit
import CoreData

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }

    func applicationWillResignActive(application: UIApplication) {
        // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
        // Use this method to pause ongoing tasks, disable timers, and throttle down OpenGL ES frame rates. Games should use this method to pause the game.
    }

    func applicationDidEnterBackground(application: UIApplication) {
        // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
        // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
    }

    func applicationWillEnterForeground(application: UIApplication) {
        // Called as part of the transition from the background to the inactive state; here you can undo many of the changes made on entering the background.
    }

    func applicationDidBecomeActive(application: UIApplication) {
        // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    }

    func applicationWillTerminate(application: UIApplication) {
        // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
    }

    // MARK: - Core Data stack

    lazy var applicationDocumentsDirectory: NSURL = {
        // The directory the application uses to store the Core Data store file. This code uses a directory named "at.meinhard-kissich.SWSCore" in the application's documents Application Support directory.
        let urls = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)
        return urls[urls.count-1]
        }()

    lazy var managedObjectModel: NSManagedObjectModel = {
        // The managed object model for the application. This property is not optional. It is a fatal error for the application not to be able to find and load its model.
        let modelURL = NSBundle.mainBundle().URLForResource("SWS", withExtension: "momd")!
        return NSManagedObjectModel(contentsOfURL: modelURL)!
        }()

    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("SWS.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()
            }
        }
    }



}

After that I tried to write a new dataset to the database

    let appDelegate = (UIApplication.sharedApplication().delegate as! AppDelegate)
    let managedContext = appDelegate.managedObjectContext

    let entity = (NSEntityDescription.insertNewObjectForEntityForName("WeatherData", inManagedObjectContext: managedContext)) as NSManagedObject


    entity.setValue(32, forKey: "id")


    do {
        try managedContext.save()
    } catch let error as NSError {
        print("Could not save \(error), \(error.userInfo)")
    }
    print("obj saved")

Unfortunately, I always get the following error:

fatal error: unexpectedly found nil while unwrapping an Optional value

in this line:

let modelURL = NSBundle.mainBundle().URLForResource("SWS", withExtension: "momd")!

Where could be the problem?

  • Thank you!

解决方案

Where could be the problem?

It's simple: you're force-unwrapping the Optional value returned by NSBundle.mainBundle().URLForResource("SWS", withExtension: "momd") with !, meaning that if the value doesn't exist the application will crash. And indeed the problem here is that NSBundle can't find your resource.

这篇关于将iOS Core数据添加到现有项目 - 在解包可选值时出错的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆