Reputation: 638
I'm still new at Core Data.
I'm trying to loop three times over an array and at each loop, I'm saving the index number.
But it's only showing the last index number when fetching the results. It's overriding everything that was inserted before.
My code is written in the AppDelegate.
Here's my code:
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *tagsDB = [NSEntityDescription insertNewObjectForEntityForName:@"Tags" inManagedObjectContext:context];
for (int i = 0 ; i < 3 ; i++)
{
[tagsDB setValue:i forKey:@"ID"];
}
[self saveContext];
...
- (void)saveContext
{
NSError *error = nil;
NSManagedObjectContext *managedObjectContext = self.managedObjectContext;
if (managedObjectContext != nil) {
if ([managedObjectContext hasChanges] && ![managedObjectContext save:&error]) {
// 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();
}
}
}
Upvotes: 6
Views: 1187
Reputation: 788
You have to create your entity for each value.
NSManagedObjectContext *context = [self managedObjectContext];
for (int i = 0 ; i < 3 ; i++)
{
NSManagedObject *tagsDB = [NSEntityDescription insertNewObjectForEntityForName:@"Tags" inManagedObjectContext:context];
[tagsDB setValue:i forKey:@"ID"];
}
[self saveContext];
Upvotes: 8
Reputation: 14304
In your for loop - the code that gets reiterated simply changes the value of the new inserted item. What you need to be doing in the for loop is insertNewObjectForEntityForName
which will insert a new, separate entity for each iteration.
Upvotes: 1