简体   繁体   中英

How to save a string to Core Data Swift

I'm creating a signup form with multiple view controllers as "pages" and I need the information from one view controller such as 'First name' and 'last name' or 'email address' to another view controller. I decided I'm going to use core data to save the strings and retrieve them from another view controller rather than create a global struct for every view controller (because it crashes every time I try and implement it). Heres my code:

@IBAction func nextBtnWasPressed(_ sender: Any) {

        if firstNameText.text != "" && lastNameText.text != "" {
            //Core Data User Information
            var userInfo = UserInfo() // The Name of the Core Data Entity
            var firstName: String = firstNameText.text!
            userInfo.firstName = firstName

            do {
            try NSManagedObjectContext.save(firstName)//Need Fixing
        } catch {
            fatalError("Failure to save context: \(error)")
        }
        performSegue(withIdentifier: "toBirthdate", sender: self)
    } else {
        nextBtn.alpha = 0.5
    }
}

Here is the error log : 'Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '-[UserInfo setFirstName:]: unrecognized selector sent to instance 0x600001530e80' Full error log: View Here

Well, at first I was going to give the obvious answer which is that, in your Core Data data model, your UserInfo entity does not have a firstName attribute.

That's still possible, but then I looked at the full transcript you posted and saw that, a couple hundred microseconds before this error is another error:

Failed to call designated initializer on NSManagedObject class 'UserInfo'

I suspect this error indicates that you have initialized your managed object with init() . This is a common mistake of first-time Core Data users. Ensure that you are initializing your UserInfo object like this:

let userInfo  = UserInfo.init(entity: entityDescription, insertInto: context);

or if your deployment target is iOS 10 or later, you can use the newer cleaner method:

let userInfo  = UserInfo.init(context: context)

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