I wrote an ios application in order to save a data to core data and then fetch it with the following code:
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error;
NSManagedObject *failedBankInfo = [NSEntityDescription
insertNewObjectForEntityForName:@"UserData"
inManagedObjectContext:context];
[failedBankInfo setValue:[NSNumber numberWithInt:1] forKey:@"userId"];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:@"UserData" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSLog(@"Name: %@", [info valueForKey:@"userId"]);
}
There no problem in here. But After I close my application and modify the setvalue to 2, I only receive the last data which is 2. Earlier data (1) gets deleted.
What should I do to keep the data entries even after I close my application.
Thank You!
You need to create a
UIManagedDocumentto save the Core Data information. I usually create theUIManagedDocumentas a property of the class. For the example I have created aUIManagedDocumentcalledtheManagedDocument:Then I create a method called
documentIsReadythat is called when the document has been successfully created or opened (opened if it is already present, created otherwise). I will also keep the context as a property. Here it is calledcontext. I also added in your code:You will then want to close the document when you are done using: