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();
}
}
}
Deleting stored data is almost as simple as updating it. All we have to do is to delete the specific Order from the viewContext. Then, since the @FetchRequest will automatically detect that the Order was deleted, it will update our ContentView accordingly and remove the row from the table with a nice default animation.
How to store data for a player persistently between game sessions. Sending the player score from the server to the client to display in the UI. How to spawn the last equipment the player used when they join. For your game to store data persistently for players, you will need to enable player storage.
If the entity has not yet been saved to the database (that is, it is tracked as added) then it will be removed from the context and will no longer be inserted when SaveChanges is called. You can combine multiple Add/Update/Remove operations into a single call to SaveChanges. For most database providers, SaveChanges is transactional.
You learned how to use Core Data in SwiftUI to store data persistently. We talked through all basic CRUD operations: Creating, reading, updating, and deleting data.
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];
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With