Wasim Akram Wasim Akram - 1 year ago 103
Swift Question

How to save multiple records in core data

I am new to Swift. I am worrying about how to implement a feature. I have a table view with multiple selection if user select and deselect that should save in an array and that records in an array save in to core data later. I have tried many ways but it is storing only one record.

Answer Source

You have to traverse your array for each record and create a new [NSEntityDescription insertNewObjectForEntityForName] object. Below is the example which is a common method which accept coreDataEntityName and an array of records. Lets say your entity name is Record which has attribute as name then you can set the attribute from the array and then save the context.

    func insertItems(coreDataTable : String, records: NSArray) -> Bool {
        let error: NSError?
        for(item in records as NSDictionary!) {
            let entity = NSEntityDescription.entityForName(coreDataTable, inManagedObjectContext: self.managedContext)
            var record = NSManagedObject(entity: entity!, insertIntoManagedObjectContext: managedContext) as Record!
            record.name = item["name"]
            if (!self.mainObjectContext.save()) {
                // Replace this implementation with code to handle the error appropriately.
                // abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
                NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
                return false
    return true

This will add all your records.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download