简体   繁体   中英

Problems with error code when writing to core data with Swift

I am new to coding with Swift and I am trying to write two text fields into my core data file. I have figured out most of the code I need by searching on line but I am getting an error that I can't figure out. I have posted the entire save function code below but I am getting a "Cannot use optional chaining on non-optional value of type 'NSManagedObjectContext'" error on the line starting with managedObjectContext.

@IBAction func saveData(sender: AnyObject) {
    let entityDescription = NSEntityDescription.entityForName("MatchData", inManagedObjectContext: managedObjectContext)

    let matchData = MatchData(entity: entityDescription!, insertIntoManagedObjectContext: managedObjectContext)

    matchData.teamNumber = teamNumber.text
    matchData.matchNumber = matchNumber.text

    var error: NSError?

    managedObjectContext?.save(error)

    if let err = error {
        status.text = err.localizedFailureReason
    } else {
        teamNumber.text = ""
        matchNumber.text = ""
    }
}

I am working with the newest version of Xcode and I think the issue has something to with the changes in Swift but I can't figure it out since I am a novice. Any help debugging would be appreciated.

Where is the do, try, catch statement? If you want to save objects to the managedObjectContext you must be use this statement like so: do { try manaagedObjectContext.save() } catch { // handle error }

Please try this out! Hope it helps

`@IBAction func saveData(sender: AnyObject) {

let entityDescription:MatchData = NSEntityDescription.insertNewObjectForEntityForName("MatchData", inManagedObjectContext: managedObjectContext) as! MatchData

entityDescription.teamNumber = self.teamNumber.text
entityDescription.matchNumber = self.matchNumber.text

do { try managedObjectContext.save() } catch { /*Handle error*/  }

print(entityDescription) }`

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM