2014-09-13 91 views
0

我一直在嘗試做一個簡單的CoreData任務,保存數據。我確定它可以在Beta 6中運行,但在更新到Beta 7後開始出現錯誤。Beta 7中的XCode 6 Beta 6錯誤 - 可選類型的值未解包

我想我必須添加'?'要麼 '!'基於錯誤提示,但只是不夠聰明,弄清楚哪裏!

@IBAction func saveItem(sender: AnyObject) { 

    // Reference to App Delegate 

    let appDel: AppDelegate = UIApplication.sharedApplication().delegate as AppDelegate 

    // Reference our moc (managed object content) 

    let contxt: NSManagedObjectContext = appDel.managedObjectContext! 
    let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: contxt) 

    // Create instance of our data model and initialize 

    var newItem = Model(entity: ent, insertIntoManagedObjectContext: contxt) 

    // Map our attributes 

    newItem.item = textFieldItem.text 
    newItem.quanitity = textFieldQuantity.text 
    newItem.info = textFieldInfo.text 

    // Save context 

    contxt.save(nil) 
} 

錯誤說

Value of optional type 'NSEntityDescription?' not unwrapped; did you mean to use '!' or '?' 

在生產線

var newItem = Model(entity: ent, insertIntoManagedObjectContext: contxt) 

每次我似乎有明顯的錯誤,並編譯OK,點擊「保存」顯示了在調試區

fatal error: unexpectedly found nil while unwrapping an Optional value 

回答

0

錯誤是fai小小的瑣碎,這裏沒有太多可以分析的地方。嘗試改變這一點:

let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: context) 

這個

let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: context)! 

與往常一樣,新手往往忽視搬弄是非的跡象。該錯誤清楚地表明可選的是NSEntityDescription。考慮到這種類型的對象只能在給定的代碼中實例化,所以不需要天才就能猜出錯誤的位置。

Value of optional type 'NSEntityDescription?' not unwrapped; did you mean to use '!' or '?' 

而且,這裏使用實例化對象NSEntityDescription方法聲明如下:

class func entityForName(entityName: String, inManagedObjectContext context: NSManagedObjectContext) -> NSEntityDescription? 

...的?字符清晰地告訴我們,這個方法返回一個可選。

0

我相信的是,Model初始化簽名是:發生

init(entity: NSEntityDescription, insertIntoManagedObjectContext: NSManagedObjectContext) 

的編譯錯誤,因爲NSEntityDescription.entityForName返回一個可選的,所以你要解開它。

對於運行時錯誤,我的猜測是,contxt爲零,而你傳遞一個被迫展開的位置:

let ent = NSEntityDescription.entityForName("List", inManagedObjectContext: contxt) 

爲了取得代碼更安全,更清晰,我會明確地使用選配:

let contxt: NSManagedObjectContext? = appDel.managedObjectContext 
if let contxt = contxt { 
    let ent: NSEntityDescription? = NSEntityDescription.entityForName("List", inManagedObjectContext: contxt) 

    // Create instance of our data model and initialize 

    if let ent = ent { 
     var newItem = Model(entity: ent, insertIntoManagedObjectContext: contxt) 
    } 
} 

並使用調試程序&斷點檢查是否有任何提到的變量爲零。

相關問題