在函数内部抛出错误,但不在外部

时间:2015-02-25 01:41:04

标签: ios swift core-data

我一直在使用dbconnect函数中的常量和变量来允许直接访问我的核心数据变量。

当我输入这样的代码时,它可以工作:

    @IBAction func createNewGame(sender: AnyObject) {
    let entityDescription = NSEntityDescription.entityForName("StudioData", inManagedObjectContext: managedObjectContext!)
    let studioData = StudioData(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
    var error: NSError?
    managedObjectContext?.save(&error)
    if let err = error {
        println(err.localizedFailureReason)
    } else {
        println("Studio Created")
    }
    studioData.studioname = studioNameText.text
    studioData.execFirstName = firstNameText.text
    studioData.execLastName = lastNameText.text
}

但是当它像这样返回" Unresolved identifier studioData"

    @IBAction func createNewGame(sender: AnyObject) {
    dbconnect()
    studioData.studioname = studioNameText.text
    studioData.execFirstName = firstNameText.text
    studioData.execLastName = lastNameText.text
}

func dbconnect () {
    let entityDescription = NSEntityDescription.entityForName("StudioData", inManagedObjectContext: managedObjectContext!)
    let studioData = StudioData(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
    var error: NSError?
    managedObjectContext?.save(&error)
    if let err = error {
        println(err.localizedFailureReason)
    } else {
        println("Studio Created")
    }

}

我试图将代码放入一个函数中,以减少不同函数之间的重复。

我错过了什么?

1 个答案:

答案 0 :(得分:0)

错误在于studioData中未定义变量createNewGame(sender:)。由于您要使用dbconnect()的结果,我建议将创建的对象传回给调用者。有很多方法可以实现这一目标,但这里有一个:

@IBAction func createNewGame(sender: AnyObject) {
    var studioData = dbconnect()
    studioData.studioname = studioNameText.text
    studioData.execFirstName = firstNameText.text
    studioData.execLastName = lastNameText.text
}

func dbconnect () -> StudioData {
    let entityDescription = NSEntityDescription.entityForName("StudioData", inManagedObjectContext: managedObjectContext!)
    let studioData = StudioData(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)
    var error: NSError?
    managedObjectContext?.save(&error)
    if let err = error {
        println(err.localizedFailureReason)
    } else {
        println("Studio Created")
    }
    return studioData
}