I am new in iOS and I am facing a problem regarding to update value of coredata.
For Save
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *device;
if (self.device) {
// Update existing device
[device setValue:GlobalIndexPath forKey:#"key"];
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Device" inManagedObjectContext:context];
[newDevice setValue:GlobalIndexPath forKey:#"key"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
My code to fetch core data is
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"EntityName" inManagedObjectContext:context]];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
And to update I and using code
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:#"1" forKey:#"Key"];
Update code not update it add one object.
Note - GlobalIndexPath is a name of string.
But this is not working for me any suggestion. Thanks in Advcance!
You need to save the context every time you make changes to any NSManagedObject and want it to persist. Try this:
NSManagedObject* favoritsGrabbed = [results objectAtIndex:0];
[favoritsGrabbed setValue:#"1" forKey:#"Key"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
Related
I am getting only last record from coredata? below is the my code .
NSManagedObjectContext *context = ((AppDelegate*)[[UIApplication sharedApplication] delegate]).persistentContainer.viewContext;
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Company"
inManagedObjectContext:context];
[object setValue:#"infosys" forKey:#"cname"];
[object setValue:#"01" forKey:#"compID"];
[object setValue:#"Pune" forKey:#"locaation"];
[object setValue:#"wipro" forKey:#"cname"];
[object setValue:#"02" forKey:#"compID"];
[object setValue:#"Mumbai" forKey:#"locaation"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (result.count<=0) {
NSLog(#"No User Found");
}
else{
NSString *cname;
NSString *compID;
NSString *locaation;
for (NSManagedObject *obj in result) {
cname=[obj valueForKey:#"cname"];
compID=[obj valueForKey:#"compID"];
locaation=[obj valueForKey:#"locaation"];
}
NSLog(#"Store Data = %#",[NSString stringWithFormat:#"%# %# %#",cname,compID,locaation]);
}
Add objects like this,
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Company" inManagedObjectContext:context];
[object setValue:#"infosys" forKey:#"cname"];
[object setValue:#"01" forKey:#"compID"];
[object setValue:#"Pune" forKey:#"locaation"];
NSManagedObject *object2 = [NSEntityDescription insertNewObjectForEntityForName:#"Company" inManagedObjectContext:context];
[object2 setValue:#"wipro" forKey:#"cname"];
[object2 setValue:#"02" forKey:#"compID"];
[object2 setValue:#"Mumbai" forKey:#"locaation"];
NSError *error;
if (![context save:&error]) {
NSLog(#"Failed to save - error: %#", [error localizedDescription]);
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Company" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
if (result.count<=0) {
NSLog(#"No User Found");
}
else{
NSString *cname;
NSString *compID;
NSString *locaation;
for (NSManagedObject *obj in result) {
cname=[obj valueForKey:#"cname"];
compID=[obj valueForKey:#"compID"];
locaation=[obj valueForKey:#"locaation"];
NSLog(#"Store Data = %#",[NSString stringWithFormat:#"%# %# %#",cname,compID,locaation]);
}
}
I am new in iOS and I am facing problem regarding to add NSArray in Core Data as an NSString.
I am using code like this:
NSManagedObjectContext *context = [self managedObjectContext];
//Converting array as an string...
AuditIDCoreData=[NSString stringWithFormat:#"%#",idAuditarray];
AuditnameCoreData=[NSString stringWithFormat:#"%#",nameAuditarray];
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Get_Auditnames_User" inManagedObjectContext:context]];
// NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSLog(#"Result =%#",results);
NSString *Stringaudit =[NSString stringWithFormat:#"%#",idAuditarray];
ComplareArray=[devices valueForKey:#"auditname"];
ComplareArray2=[devices valueForKey:#"auditid"];
BOOL contains = [ComplareArray2 containsObject:Stringaudit];
if(contains == YES)
{
}
else
{
if (self.device) {
// Update existing device
[self.device setValue:AuditIDCoreData forKey:#"auditid"];
[self.device setValue:AuditnameCoreData forKey:#"auditname"];
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"Get_Auditnames_User" inManagedObjectContext:context];
// NSLog(#"context",newDevice);
[newDevice setValue:AuditIDCoreData forKey:#"auditid"];
[newDevice setValue:AuditnameCoreData forKey:#"auditname"];
}
//NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
Code I have Updated:
NSString *FailString =#"";
NSString *WarningString =#"";
NSManagedObjectContext *context = [self managedObjectContext];
for (int i = 0; i < idarray.count; i++){
if (self.device) {
// Update existing device
[device setValue:Audit forKey:#"auditnameId"];
[device setValue:Passarray[i] forKey:#"checklistid"];
[device setValue:CheckpointNameIDArray[i] forKey:#"checkpointid"];
[device setValue:FailString forKey:#"failreason"];
[device setValue:WarningString forKey:#"warningreason"];
[device setValue:AuditStartDate forKey:#"starttimedate"];
[device setValue:userid forKey:#"userid"];
[device setValue:imageArray[i] forKey:#"auditimage"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
} else {
// Create a new device
NSManagedObject *newDevice = [NSEntityDescription insertNewObjectForEntityForName:#"AuditPost" inManagedObjectContext:context];
[newDevice setValue:Audit forKey:#"auditnameId"];
[newDevice setValue:Passarray[i] forKey:#"checklistid"];
[newDevice setValue:CheckpointNameIDArray[i] forKey:#"checkpointid"];
[newDevice setValue:FailString forKey:#"failreason"];
[newDevice setValue:WarningString forKey:#"warningreason"];
[newDevice setValue:AuditStartDate forKey:#"starttimedate"];
[newDevice setValue:userid forKey:#"userid"];
[newDevice setValue:imageArray[i] forKey:#"auditimage"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
}
But it saves whole array in just a single string. I need to store array element one by one in Core Data as String.
How is it possible?
Can do in just simple steps.
AppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *newData;
for (int i = 0; i < array1.count; i++){
newData = [NSEntityDescription insertNewObjectForEntityForName:#"yourEntityName" inManagedObjectContext:context];
[newData setValue:array1[i] forKey:#"sub-entities"];
[newData setValue:array2[i] forKey:#"sub-entities"];
}
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}else {
NSLog(#"Data saved successfully ..");
}
Saving multiple array array1 & array2 to the sub-entities of an entity.
You can convert it as follow
NSArray *arrayToBeConvertedInToString = #[#"This", #"is", #"an", #"array"];
NSString * result = [[arrayToBeConvertedInToString valueForKey:#"description"] componentsJoinedByString:#" "];
NSLog(#"Array in string: %#", result);
You can use method explained by Richard G
I ll suggest you to convert it into NSData and store it as transferable in coreData
Converting into NSData
NSData *data = [NSKeyedArchiver archivedDataWithRootObject:arrayName];
Storing into CoreData
[newManagedObject setValue:nsData forKey:#"auditid"];
Be sure you have changed datatype to transformable in coredata
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 am trying to update int data by using CoreData but I think I am missing some parts before updating the object. Here what I am trying to do to save the int value. Here I want to both save and update only first object value.
- (IBAction)btnYakClicked:(UIButton *)sender
{
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"Kalorimetre" inManagedObjectContext:context]];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSManagedObject* kaloriObject = [results objectAtIndex:0];
NSNumber *valWeek = [NSNumber numberWithInteger:300];
NSNumber *valMonth = [NSNumber numberWithInteger:1000];
[kaloriObject setValue:valWeek forKey:#"thisweek"];
[kaloriObject setValue:valWeek forKey:#"thismonth"];
}
I don't see the line where you're saving it. For example:
NSError *saveError;
if (![context save:&saveError]) {
NSLog(#"Error: %# %#", saveError, [saveError localizedDescription]);
}
It might also be a good idea to limit the fetch request since you're only looking for the first object:
[request setFetchLimit:1];
I would hope that this would improve performance but cannot confirm.
In the code below (in ViewDidLoad), I import a JSON file into an iOS project, and then persist the data using Core Data and, at the end, perform a fetch request successfully. However, after I remove the code that imports the file and persists the data, the fetch request starts returning (null). Based on the code below, can you explain why this is happening?
id delegate = [[UIApplication sharedApplication] delegate];
self.managedObjectContext = [delegate managedObjectContext];
NSError* err = nil;
NSString* dataPath = [[NSBundle mainBundle] pathForResource:#"inventorydata" ofType:#"json"];
NSArray* inventoryData = [NSJSONSerialization JSONObjectWithData:[NSData dataWithContentsOfFile:dataPath]
options:kNilOptions
error:&err];
if(err) NSLog(#"Error %#",[err description]);
NSLog(#"Imported Data: %#", inventoryData);
[Questions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Inventory *partsInfo= [NSEntityDescription
insertNewObjectForEntityForName:#"Inventory"
inManagedObjectContext:self.managedObjectContext];
partsInfo.name = [obj objectForKey:#"name"];
partsInfo.sku = [obj objectForKey:#"sku"];
Supplier *supplierInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"Supplier"
inManagedObjectContext:self.managedObjectContext];
supplierInfo.supplierId = [obj objectForKey:#"supplierId"];
[supplierInfo setValue:[NSSet setWithObject:partsInfo ] forKey:#"partData"];
}];
NSError *error;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Supplier"
inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
self.fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (Supplier *info in self.fetchedObjects) {
NSLog(#"supplierId: %#", info.supplierId);
}
Try this.
[Questions enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
Inventory *partsInfo= [NSEntityDescription
insertNewObjectForEntityForName:#"Inventory"
inManagedObjectContext:self.managedObjectContext];
partsInfo.name = [obj objectForKey:#"name"];
partsInfo.sku = [obj objectForKey:#"sku"];
Supplier *supplierInfo = [NSEntityDescription
insertNewObjectForEntityForName:#"Supplier"
inManagedObjectContext:self.managedObjectContext];
supplierInfo.supplierId = [obj objectForKey:#"supplierId"];
[supplierInfo setValue:[NSSet setWithObject:partsInfo ] forKey:#"partData"];
}];
//Add this code : need to save database.
[delegate saveContext];
// You should add this method in AppDelegate.m
- (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();
}
}
}