how to update core data entered values - ios

[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];

Related

Delete specific data from specific entity from core data in objective c?

I have two entity in my core data named "History" and "Favorite". i want to delete some specific data like "Dhaka" from "History" entity. How to delete this. Thanks in advance.
Hope it will help you.
NSString* aType = #"History";
NSString *tp = #"Dhaka";
NSFetchRequest * request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:aType inManagedObjectContext:self.managedObjectContext]];
NSPredicate* predicate = [NSPredicate predicateWithFormat:#"(type == %#)",tp ]; //where type is the attribute
[request setPredicate:predicate];
NSArray* ar = [self.managedObjectContext executeFetchRequest:request error:nil];
NSLog(#"############# Data from DB : %#",ar);
for(id anObj in ar){
[managedObjectContext deleteObject:anObj];
}
[self.managedObjectContext save:nil];
predicate=nil;
try this:
objAppDelegate = (AppDelegate *)[UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [objAppDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:#"History"];
NSArray *recordArray =[[NSArray alloc]initWithArray:[context executeFetchRequest:request error:nil]];
objDataClass = [recordArray objectAtIndex:0]; // here objDataClass is a instance of DataClass derived from NSObject which define column name
[context deleteObject:objDataClass]; // Delete particular data with index
if ([context hasChanges])
{
[context save:nil];
}
else
{
NSLog(#"Object Deleted.....");
}
Hope it will help you. :)

How to update record in core data in iOS?

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];
}

How to save and retrieve two arrays in Core Data in iOS6

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"];
}

Add multiple/sequential rows - populate DB in Coredata

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];
}

ios core data - copy entity records to another entity

I have 2 entity, Units and BUnits, the Units entity have a data that will be replaced many time, and the BUnits will be the backup of the Units entity before clearing it's data.
So, I've created a NSManagedObjectContext instance, then I've retrive an instance for each entity by using
NSManagedObjectContext *context = [mainDelegate managedObjectContext];
NSEntityDescription *unitsEntity = [NSEntityDescription entityForName:#"Units" inManagedObjectContext:context];
NSEntityDescription *bUnitsEntity = [NSEntityDescription entityForName:#"BUnits" inManagedObjectContext:context];
but i've didn't managed to copy the Units entity records to the BUnits entity, other than make a loop for each records, but i believe that there is a better solution.
What do you think about this, is there a better solution?
UPDATE:
The solution i've used in case anyone could use it is in my answer, I think there is a better way to do this, i will keep checking for it and i will update the question if i found anything.
Here is what i've used, using looping for each record:
- (void) copyEntities:(NSString *)sourceEntity And:(NSString *)destinationEntity {
NSManagedObjectContext *context = [mainDelegate managedObjectContext];
NSEntityDescription *Units = [NSEntityDescription entityForName:sourceEntity inManagedObjectContext:context];
NSEntityDescription *BUnits = [NSEntityDescription entityForName:destinationEntity inManagedObjectContext:context];
NSFetchRequest *dataRequest = [[NSFetchRequest alloc] init];
[dataRequest setEntity:Units];
NSError *error = nil;
NSArray *dataArray = [context executeFetchRequest:dataRequest error:&error];
for (UnitsClass *unit in dataArray) {
UnitsClass *savedUnits;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:BUnits];
NSPredicate *pred = [NSPredicate predicateWithFormat:#"(code = %#)", unit.code];
NSPredicate *pred1 = [NSPredicate predicateWithFormat:#"(code2 = %#)", unit.code2];
NSPredicate *compoundPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:pred, pred1, nil]];
[request setPredicate:compoundPredicate];
NSError *error = nil;
NSArray *objects = [context executeFetchRequest:request error:&error];
//this if to indicate if we inserting to the BUnits or updating it.
if ([objects count] > 0) {
//Found the record, update The info
savedUnits = [objects objectAtIndex:0];
} else {
savedUnits = [NSEntityDescription insertNewObjectForEntityForName:destinationEntity inManagedObjectContext:context];
}
savedUnits.code = unit.code;
/*Add your updated info*/
NSError *errors;
if (![context save:&errors]) {
NSLog(#"Whoops, couldn't save: %#", [errors localizedDescription]);
}
}
NSLog(#"BUnits count = %d",[context countForFetchRequest:[NSFetchRequest fetchRequestWithEntityName:destinationEntity] error:&error]);
}
Based on the given information, there is no better way than looping each unit object and creating the backup object.

Resources