简体   繁体   中英

How to save in core data?

I have been searching for some sample code on how to store an NSArray in Core Data for awhile now, but haven't had any luck. I now know how to store data like NSStrings, NSDate and other type but struggling to store an NSArray. I've read so many articles saying you must write it to the disk and write to a file, but I can't seem to understand it.

import UIKit

class Person: NSObject {
var fullName : String!
var mobileNumbers : [Mobile]!
}

import UIKit

class Mobile: NSObject {

    var mobileNumber : String!
 }

// core data save method

below method shows save to core data

 func save(name: Person) {


     guard let appDelegate =
            UIApplication.shared.delegate as? AppDelegate else {
                return
        }
         var managedContext = NSManagedObjectContext()

        if #available(iOS 10.0, *) {
             managedContext = appDelegate.persistentContainer.viewContext
        } else {
            // Fallback on earlier versions
        }


        let entity = NSEntityDescription.entity(forEntityName: "Contact",in: managedContext)!

        let person = NSManagedObject(entity: entity,insertInto: managedContext)

         person.setValue(name.fullName, forKeyPath: "fullName")

       if let mob = name.mobileNumberList{

            let arch = NSKeyedArchiver.archivedData(withRootObject: mob[0])
            print(arch)

            person.setValue(arch, forKey: "mobileNumberList")

        }



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


    }

U can store an array in core data

in .xcdatamodeld file create Entity name "Contact" and add an attribute(of any name) and select type "Transformable".

then

 let entity = NSEntityDescription.entity(forEntityName: "Contact",in: managedContext)!

 let person = NSManagedObject(entity: entity,insertInto: managedContext)

 person.setValue("YourArrayName", forKeyPath: "YourArrayKeyName")

Check this link for more details of working of core data in swift

try this :-

   guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else {return}

                let managedContext = appDelegate.persistentContainer.viewContext
                let user:UserModel =  NSEntityDescription.insertNewObject(forEntityName: "User", into: managedContext) as! UserModel


                user.name = txtName.text!

              var arr: [UInt32] = [32, 4, UInt32.max]
         let data = Data(buffer: UnsafeBufferPointer(start: &arr, count: arr.count))                

                user.arr = data



                do {
                    try managedContext.save()


                } catch let error as NSError
                {
                    print("Could not save. \(error), \(error.userInfo)")
                }

Short answer is that you can't.

You have 2 options:

  1. Create a new Core Data Entity for your object Mobile (in your data model), and use the 1:many relationship to link to Person. Core Data will automatically generate methods (eg addToMobiles(_ value: Mobile)) for you.

  2. Model an attribute of Person as "mobileNumbers" as an NSString. Then store mobile numbers as a JSON blob (or any other structure)

The first may be more "correct", but if you are only storing numbers, the second is easier.

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