Reputation: 51
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.
Upvotes: 2
Views: 3369
Reputation: 2636
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]);
//abort();
return false
}
}
return true
}
This will add all your records.
Upvotes: 3