Reputation: 1751
I want to insert the data in coredata in swift. Iam using the following code to insert the bulk data into database table at once. But it always inserts single row and keep on updating the row in table.
Can anyone please help me to resolve this.
func insertIntoTestClass(testClassArray : [DBTestClass])
{
let managedObject = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
let table1 = NSEntityDescription.insertNewObjectForEntityForName("testClass", inManagedObjectContext: managedObject) as! testClass
for i in 0..<checklistConfiguration.count
{
let insertArray = checklistConfiguration[i]
table1.test1 = insertArray.test1!
table1.test2 = insertArray.test2!
table1.test3 = insertArray.test3!
table1.test4 = insertArray.test4!
}
do{
try managedObject.save()
}
catch
{
let returnError = error as NSError
print("\(returnError)")
}
}
Upvotes: 0
Views: 218
Reputation: 4050
From what I can see in your code, you are not creating new instances of your testClass
object instead you are updating the properties of the only one created right before the loop.
You should move the creation of table1
inside the loop so that new instances can be created on each iteration of the loop.
For efficiency, you should also save your managed object context after the loop.
func insertIntoTestClass(testClassArray : [DBTestClass])
{
let managedObject = (UIApplication.sharedApplication().delegate as! AppDelegate).managedObjectContext
for i in 0..<checklistConfiguration.count
{
let table1 = NSEntityDescription.insertNewObjectForEntityForName("testClass", inManagedObjectContext: managedObject) as! testClass
let insertArray = checklistConfiguration[i]
table1.test1 = insertArray.test1!
table1.test2 = insertArray.test2!
table1.test3 = insertArray.test3!
table1.test4 = insertArray.test4!
}
do{
try managedObject.save()
}
catch
{
let returnError = error as NSError
print("\(returnError)")
}
}
}
Upvotes: 1