How do you insert multiple/sequential new rows in coredata and xcode?
-(void)LoadDB{
CoreDataAppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
context = [appdelegate managedObjectContext];
NSManagedObject *newPref;
newPref = [NSEntityDescription
insertNewObjectForEntityForName:NSStringFromClass([Preference class])
inManagedObjectContext:context];
NSError *error;
[newPref setValue: #"0" forKey:#"pid"];
[context save:&error];
[newPref setValue: #"1" forKey:#"pid"];
[context save:&error];
}
The code above just over writes the previous entry. What is the correct procedure to insert the next row?
You need a new insert statement for each core data managed object. Otherwise you are only editing the existing MO. Also, you only need to save once at the end.
-(void)LoadDB{
CoreDataAppDelegate *appdelegate = [[UIApplication sharedApplication]delegate];
context = [appdelegate managedObjectContext];
NSManagedObject *newPref;
NSError *error;
newPref = [NSEntityDescription
insertNewObjectForEntityForName:NSStringFromClass([Preference class])
inManagedObjectContext:context];
[newPref setValue: #"0" forKey:#"pid"];
newPref = [NSEntityDescription
insertNewObjectForEntityForName:NSStringFromClass([Preference class])
inManagedObjectContext:context];
[newPref setValue: #"1" forKey:#"pid"];
// only save once at the end.
[context save:&error];
}
Related
I hope it's a duplicate of other links like: How to update existing object in Core Data?
But my scenario is little bit different.
The thing is I created one Sample Core Data Project.
Step 1: I have 3 ViewController classes
In 1st Screen: I created one field in core data "password" ==> I saved using code like:
NSManagedObjectContext *context = [self managedObjectContext];
// Create a new userInfo
NSManagedObject *newuserInfo = [NSEntityDescription insertNewObjectForEntityForName:#"UserInfo" inManagedObjectContext:context];
[newuserInfo setValue:self.passwordTxtFldRef.text forKey:#"password"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
// NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
In 2nd Screen: I have two textfields like: Oldpassword & newpassword
. Here I saved old password in NSUserDefaults and in 2nd screen i checked the condition weather the oldpassword is correct or not --> It's perfect.
Here my requirement is I want to update Oldpassword to newpassword ---> in 2nd screen itself.
How can I do this? Can you please help me out regarding this?
Here i use code like:
-(void)getSavedDataFromCoreData{
NSManagedObjectContext *context = [self managedObjectContext];
NSEntityDescription *entitydesc = [NSEntityDescription entityForName:#"UserInfo" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entitydesc];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"password like %#",oldPasswordStr];
[request setPredicate:predicate];
NSError *error;
NSArray *matchingData = [context executeFetchRequest:request error:&error];
if(matchingData.count<=0){
//NSLog(#"Cancel");
}else{
for(NSManagedObject *obj in matchingData){
[obj setValue:alertTextField2.text forKey:#"password"];
}
[context save:&error];
NSMutableArray *array3 = [matchingData valueForKey:#"password"];
NSString *value3 = [array3 objectAtIndex:0];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setValue:value3 forKey:#"savedPassword"];
[defaults synchronize];
[self showGeneralAlertMessage:#"Password Changed Successfully" withTitle:#"Success"];
}
}
This will help you to update the value.
-(void)updateDataInCoreData
{
NSManagedObjectContext *context = appDelegate.managedObjectContext;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"User" inManagedObjectContext:context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"number == %#",userDict[#"number"]];
[fetchRequest setPredicate:predicate];
[fetchRequest setFetchLimit:1];
[fetchRequest setEntity:entity];
NSError *error;
NSArray *arrResult = [context executeFetchRequest:fetchRequest error:&error];
User *entity1 = arrResult[0];
entity1.number = #"123456";
[appDelegate saveContext];
}
I have save a NSARRAY in my nscoredatabase in binarydata type attribute saved with this code
AppDelegate *AppDelegate = [[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[AppDelegate managedObjectContext];
//guardar array
NSData *arrayData = [NSKeyedArchiver archivedDataWithRootObject:roll];
NSManagedObject *newContact;
newContact = [NSEntityDescription
insertNewObjectForEntityForName:#"Horarios"
inManagedObjectContext:context];
[newContact setValue:arrayData forKey:#"valor"];
NSError *error;
[context save:&error];
But i dont know how to get it back from the data store to work again with this NSARRAY
Someone can help me?
Try this code:
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Horarios"];
NSError *error;
NSArray *matches = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
Solved adding this line
[fetchRequest setReturnsObjectsAsFaults:NO];
[newVehicle setValue: _txtFieldVehicleNumber.text forKey:#"number"];
[newVehicle setValue: lblFuelType.text forKey:#"fueltype"];
[newVehicle setValue: lblFuelUnit.text forKey:#"fuelunit"];
[newVehicle setValue: lblDistanceUnit.text forKey:#"distanceunit"];
I want to update my core data entity named "Vehicle", for that entity I have several attributes and I want to update some of them but not all when I select particular attribute from the entity.
So what should I do ??
you can do the following (approximate code. Implement error handling and check syntax).
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:#"Vehicle"];
NSPredicate *predicate=[NSPredicate predicateWithFormat:#"vehicle_id==%#",vehicle_id]; // If required to fetch specific vehicle
fetchRequest.predicate=predicate;
Vehicle *newVehicle=[[self.managedObjectContext executeFetchRequest:fetchRequest error:nil] lastObject];
[newVehicle setValue: _txtFieldVehicleNumber.text forKey:#"number"];
[newVehicle setValue: lblFuelType.text forKey:#"fueltype"];
[newVehicle setValue: lblFuelUnit.text forKey:#"fuelunit"];
[newVehicle setValue: lblDistanceUnit.text forKey:#"distanceunit"];
[self.managedObjectContext save:nil]
Get an entity from core data:
VVdAppDelegate *delegate = (VVdAppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *managedObjectContext = [delegate managedObjectContext];
NSEntityDescription *entityDescriptionDelegate = [NSEntityDescription entityForName:#"entityName" inManagedObjectContext:managedObjectContext];
NSFetchRequest *requestData = [[NSFetchRequest alloc] init];
[requestData setEntity:entityDescriptionDelegate];
NSError *error;
If there are more than an NSManagedObject
NSArray *objectsArray = [managedObjectContext executeFetchRequest:requestData error:&error];
for (NSManagedObject *object in objectsArray) {
// Here update values of every object
}
// And save values to core data
[managedObjectContext save:&error];
I have two arrays
retrievedNamesMutableArray
retrievedImagesArray
which I am saving in Core Data. Although the saving operation is successful, when I fetch data, it seems to fetch either Names or Images but not both. I assume I can store a NSDictionary in Core Data but can't seem to figure out a way to do it.
This is what I am doing to save to Core Data.
-(void)saveToPhoneDatabase
{
AddressBookAppDelegate *appDelegate =[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newContact;
/* I assume this can be done but can't figure out proper process.
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc]init];
[dictionary setObject:self.retrievedNamesMutableArray forKey:#"NamesArray"];
[dictionary setObject:self.retrievedImagesArray forKey:#"ImagesArray"];
*/
for (NSString *object in self.retrievedNamesMutableArray)
{
newContact = [NSEntityDescription insertNewObjectForEntityForName:#"AddressBook" inManagedObjectContext:context];
[newContact setValue:#"GroupOne" forKey:#"groups"];
[newContact setValue:object forKey:#"firstName"];
}
for (UIImage *img in self.retrievedImagesArray)
{
newContact = [NSEntityDescription insertNewObjectForEntityForName:#"AddressBook" inManagedObjectContext:context];
[newContact setValue:img forKey:#"photo"];
NSLog(#"Saved the photos of Array");
}
[context save:nil];
}
This is how I fetch.
-(void)fetchFromPhoneDatabase
{
AddressBookAppDelegate *appDelegate =[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"AddressBook" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSError *error;
self.arrayForTable = [context executeFetchRequest:request error:&error];
NSLog(#"contents from core data = %#",self.arrayForTable);
[self.tableView reloadData];
}
Your first loop creates objects containing a name but no image, and your second loop create different objects containing an image but no name.
Assuming (from your previous questions) that both arrays have the same size, you should
create only one object for each name/image:
for (NSUInteger i = 0; i < [self.reterivedNamesMutableArray count]; i++) {
NSString *object = self.reterivedNamesMutableArray[i];
UIImage *img = self.reterivedImagesArray[i];
newContact = [NSEntityDescription insertNewObjectForEntityForName:#"AddressBook" inManagedObjectContext:context];
[newContact setValue:#"GroupOne" forKey:#"groups"];
[newContact setValue:object forKey:#"firstName"];
[newContact setValue:img forKey:#"photo"];
}
I use core data in my application. When I delete object with [context deleteObject:obj], object is not deleted only with empty fields. How can I delete object permanently? Thanks in advanced. I use table view and when this view is filled with data from core data, there are empty rows where were deleted objects. This is the code:
LNAppDelegate *appDelegate = [[UIApplication sharedApplication] delegate];
self.context = [appDelegate managedObjectContext];
self.accounts = [[NSArray alloc] init];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Accounts" inManagedObjectContext:self.context];
[fetchRequest setEntity:entity];
NSError *error;
self.accounts = [self.context executeFetchRequest:fetchRequest error:&error];
Are you making sure to save the context after you make the change?
NSError *error = nil;
if(![self.managedObjectContext save:&error])
{
/*
//Handle error
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
}
Also make sure that you are referencing the correct context, as you can have more than one.