iOS sqlite storing null value without calling setValue - ios

I am trying to store product in sqlite. When i setValue for database entity then i store correct value.
But problem is that i make a check if product is already in database then it should not add same product again. But next time it store NULL value in database.
Although i am not calling [addToFav setValue:#"My Value"];
Simply its check in for loop. When my loop runs it won't go in first condition where i make counter if(count == 0)
I don't know where from its storing NULL value. While i am not calling it any where else. So how its storing NULL value in database ?
- (IBAction)buttonAddToFavourite:(id)sender {
int count = 0;
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error=nil;
NSManagedObject *addToFav = [NSEntityDescription insertNewObjectForEntityForName:#"Favourite" inManagedObjectContext:context];
NSString *dish = [results objectForKey:#"id"];
fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Favourite" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
NSString *id1 = [info valueForKey:#"dishid"];
if ([id1 isEqualToString:dish]) {
count = count +1;
}
}
if (count == 0) {
[addToFav setValue:[results objectForKey:#"id"] forKey:#"dishid"];
[CSNotificationView showInViewController:self
tintColor:[UIColor greenColor]
image:[UIImage imageNamed:#"sucess"]
message:#"Saved As Favourite."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
else if (count > 0){
[CSNotificationView showInViewController:self
tintColor:[UIColor redColor]
image:[UIImage imageNamed:#"warning"]
message:#"Dish Already Added."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}

- (IBAction)buttonAddToFavourite:(id)sender {
NSError *error = nil;
NSString *dishId = results[#"id"];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Favourite"];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"dishid == %#", dishId]];
NSArray *fetchedObjects = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
if (fetchedObjects.count) {
[CSNotificationView showInViewController:self
tintColor:[UIColor redColor]
image:[UIImage imageNamed:#"warning"]
message:#"Dish Already Added."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
}
else {
Favourite *obj = [NSEntityDescription insertNewObjectForEntityForName:#"Favourite" inManagedObjectContext:self.managedObjectContext];
obj.dishid = dishId;
[CSNotificationView showInViewController:self
tintColor:[UIColor greenColor]
image:[UIImage imageNamed:#"sucess"]
message:#"Saved As Favourite."
duration:2.0f];
[self.permanentNotification setShowingActivity:YES];
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
}

Related

coredata issue fetching data

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

How to enable and disable tableview cell according to array count in objective c

I am new in iOS and I am facing problem regarding to enable and disable cell according to array count
My code is like this
countcellbtn.text=[NSString stringWithFormat:#"%lu",(unsigned long)ComplareArray.count];
I am getting array count I need to disable cell according to array count.
Exact Issue: I have taken Button On Button click I am saving data on
the core data and on popup I update it. So If I Directly click on
third row app get crash.
Thanks in Advance!
I am saving data on button click and updating on popup click like this
But When I directly click on 3 rd cell app get crash because it index value get change
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *STI=#"STI";
AuditNextTableViewCell *cell = (AuditNextTableViewCell *)[tableView dequeueReusableHeaderFooterViewWithIdentifier:STI];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"AuditNextTableViewCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
cell.accessoryType=UITableViewCellAccessoryNone;
}
cell.audittitlelbl.text=[NSString stringWithFormat:#"%#",[idarray objectAtIndex:indexPath.row]];
cell.nameidlbl.text=[NSString stringWithFormat:#"%#",[CheckpointNameIDArray objectAtIndex:indexPath.row]];
cell.passlbl.text=[NSString stringWithFormat:#"%#",[Passarray objectAtIndex:indexPath.row]];
cell.faillbl.text=[NSString stringWithFormat:#"%#",[Failarray objectAtIndex:indexPath.row]];
cell.warninglbl.text=[NSString stringWithFormat:#"%#",[Warningarray objectAtIndex:indexPath.row]];
cell.nalbl.text=[NSString stringWithFormat:#"%#",[NAarray objectAtIndex:indexPath.row]];
cell.popuplbl.text=[NSString stringWithFormat:#"%#",[Popuparray objectAtIndex:indexPath.row ]];
// cell.remarklbl.text=[NSString stringWithFormat:#"%#",[PFWNAArray objectAtIndex:indexPath.row]];
DataModel *model2 = [AuditTextBoxarray objectAtIndex:indexPath.row];
cell.lblAuditTextBox.text=model2.AuditTextBoxString;
//cell.lblAuditTextBox.text=[NSString stringWithFormat:#"%#",[AuditTextBoxarray objectAtIndex:indexPath.row]];
cell.AuditCountlbl.text=[NSString stringWithFormat:#"%ld)", (long)indexPath.row +1];
cell.CaptureImage.image = [imageArray objectAtIndex:indexPath.row];
// tag add on buttons
cell.passbtn.tag = indexPath.row;
cell.failbtn.tag = indexPath.row;
cell.wipbtn.tag = indexPath.row;
cell.nabtn.tag = indexPath.row;
cell.Photobtn.tag=indexPath.row;
cell.btnRemove.tag=indexPath.row;
//method add on buttons
[cell.passbtn addTarget:self action:#selector(btnP:) forControlEvents:UIControlEventTouchUpInside];
[cell.failbtn addTarget:self action:#selector(btnF:) forControlEvents:UIControlEventTouchUpInside];
[cell.wipbtn addTarget:self action:#selector(btnW:) forControlEvents:UIControlEventTouchUpInside];
[cell.nabtn addTarget:self action:#selector(btnNA:) forControlEvents:UIControlEventTouchUpInside];
[cell.Photobtn addTarget:self action:#selector(btnphotoClick:) forControlEvents:UIControlEventTouchUpInside];
[cell.btnRemove addTarget:self action:#selector(btnRemoveClick:) forControlEvents:UIControlEventTouchUpInside];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"AuditPost"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
ComplareArray=[devices valueForKey:#"checkpointid"];
countcellbtn.text=[NSString stringWithFormat:#"%lu",(unsigned long)ComplareArray.count];
//cell.userInteractionEnabled = (ComplareArray.count % 2 == 0);
if (![arrIndexPaths containsObject:indexPath])
{
[arrIndexPaths addObject:indexPath];
}
if (![PassarrIndexPaths containsObject:indexPath])
{
[PassarrIndexPaths addObject:indexPath];
}
//background color change on button
DataModel *model = [arrData objectAtIndex:indexPath.row];
if([model.strSelected isEqualToString:#"P"])
{
cell.passbtn.backgroundColor = [UIColor redColor];
}
else if([model.strSelected isEqualToString:#"F"])
{
cell.failbtn.backgroundColor = [UIColor yellowColor];
}
else if([model.strSelected isEqualToString:#"W"])
{
cell.wipbtn.backgroundColor = [UIColor orangeColor];
}
else if([model.strSelected isEqualToString:#"NA"])
{
cell.nabtn.backgroundColor = [UIColor blueColor];
}
else if ([model.strSelected isEqualToString:#"PA"])
{
cell.passbtn.backgroundColor=[UIColor greenColor];
}
else if ([model.strSelected isEqualToString:#"NAA"])
{
cell.nabtn.backgroundColor=[UIColor blueColor];
}
else
{
cell.passbtn.backgroundColor = [UIColor lightGrayColor];
cell.failbtn.backgroundColor = [UIColor lightGrayColor];
cell.wipbtn.backgroundColor = [UIColor lightGrayColor];
cell.nabtn.backgroundColor = [UIColor lightGrayColor];
}
[cell.contentView.layer setBorderColor:[UIColor blackColor].CGColor];
[cell.contentView.layer setBorderWidth:0.5f];
return cell;
}
//buttons methods
-(void)btnP:(UIButton *)sender
{
sender.backgroundColor = [UIColor redColor];
DataModel *model = [arrData objectAtIndex:sender.tag];
model.strSelected = #"P";
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"AuditPost"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
AuditNextTableViewCell *cell = sender.superview.superview;
NSIndexPath *indexPath = [Audittable indexPathForCell:cell];
CurrentIndexPath=indexPath.row;
NSString *String3=cell.audittitlelbl.text;
NSString *String =cell.actuallbl.text;
String2=cell.nameidlbl.text;
CGSize newSizeClient=CGSizeMake(200,200); // I am giving resolution 50*50 , you can change your need
UIGraphicsBeginImageContext(newSizeClient);
[cell.CaptureImage.image drawInRect:CGRectMake(0, 0, newSizeClient.width, newSizeClient.height)];
UIImage* newImageClient = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
NSData *imgData = [[NSData alloc] initWithData:UIImageJPEGRepresentation((newImageClient), 0.5)];
AuditImageString = [imgData base64EncodedStringWithOptions:NSDataBase64Encoding64CharacterLineLength];
CheckStringShow =#"6";
NSLog(#"String =%#",String);
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:String forKey:#"ActualStringCustom"];
[defaults setObject:String2 forKey:#"CheckPointNameID"];
NSString *FailString=#"";
NSString *WarningString=#"";
HighString=#"";
UIAlertView *testAlert = [[UIAlertView alloc] initWithTitle:#"Enter High Risk Reason"
message:String3
delegate:self
cancelButtonTitle:nil
otherButtonTitles:#"Done", nil];
textView1 = [UITextView new];
lbl = [[UILabel alloc] initWithFrame:CGRectMake(10.0, 0.0,90.0, 34.0)];
[lbl setText:#"Enter Remark"];
[lbl setFont:[UIFont systemFontOfSize:12]];
[lbl setBackgroundColor:[UIColor clearColor]];
[lbl setTextColor:[UIColor lightGrayColor]];
textView1.delegate = self;
[textView1 addSubview:lbl];
[testAlert setValue: textView1 forKey:#"accessoryView"];
[testAlert show];
NSLog(#"Text View Data =%#",textView1.text);
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error;
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"AuditPost" inManagedObjectContext:context]];
// NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSLog(#"Result =%#",results);
int imageSize = imgData.length;
NSLog(#"size of image in KB: %d ", imageSize/1024);
int OCS=imageSize/1024;
NSLog(#"OCS Image Size =%d",OCS);
if(OCS<2)
{
AuditImageString=#"";
}
ComplareArray=[devices valueForKey:#"checkpointid"];
BOOL contains = [ComplareArray containsObject:String2];
if(contains == NO)
{
if (self.device) {
// Update existing device
[device setValue:Audit forKey:#"auditnameId"];
[device setValue:String forKey:#"checklistid"];
[device setValue:String2 forKey:#"checkpointid"];
[device setValue:FailString forKey:#"failreason"];
[device setValue:WarningString forKey:#"warningreason"];
[device setValue:HighString forKey:#"highregion"];
[device setValue:AuditStartDate forKey:#"starttimedate"];
[device setValue:userid forKey:#"userid"];
[device setValue:AuditImageString 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:String forKey:#"checklistid"];
[newDevice setValue:String2 forKey:#"checkpointid"];
[newDevice setValue:FailString forKey:#"failreason"];
[newDevice setValue:WarningString forKey:#"warningreason"];
[newDevice setValue:HighString forKey:#"highregion"];
[newDevice setValue:AuditStartDate forKey:#"starttimedate"];
[newDevice setValue:userid forKey:#"userid"];
[newDevice setValue:AuditImageString forKey:#"auditimage"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
}
else
{
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"AuditPost" inManagedObjectContext:context]];
NSArray *results = [context executeFetchRequest:request error:&error];
NSManagedObject* favoritsGrabbed = [results objectAtIndex:CurrentIndexPath];
[favoritsGrabbed setValue:String forKey:#"checklistid"];
[favoritsGrabbed setValue:FailString forKey:#"failreason"];
[favoritsGrabbed setValue:WarningString forKey:#"warningreason"];
[favoritsGrabbed setValue:HighString forKey:#"highregion"];
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
//example reload table
dispatch_async(dispatch_get_main_queue(), ^{
[Audittable reloadData];
});
}
- (void)alertView:(UIAlertView *)alertView didDismissWithButtonIndex:(NSInteger)buttonIndex {
NSString *CheckString;
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
CheckString=[defaults objectForKey:#"CheckStringCommentAudit"];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"AuditPost"];
self.devices = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
NSLog(#"String 2=%#",String2);
NSManagedObjectContext *context = [self managedObjectContext];
compareCommentArray=[devices valueForKey:#"checkpointid"];
BOOL contains = [compareCommentArray containsObject:String2];
if(contains == YES)
{
if([CheckStringShow isEqualToString:#"4"])
{
NSLog(#"Text Value =%#",textView1.text);
NSString *String=textView1.text;
DataModel *model = [AuditTextBoxarray objectAtIndex:CurrentIndexPath];
model.AuditTextBoxString = String;
dispatch_async(dispatch_get_main_queue(), ^{
[Audittable reloadData];
});
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
///
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"AuditPost" inManagedObjectContext:context]];
// NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSManagedObject* favoritsGrabbed = [results objectAtIndex:CurrentIndexPath];
[favoritsGrabbed setValue:String forKey:#"failreason"];
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
else if ([CheckStringShow isEqualToString:#"5"])
{
NSLog(#"Text Value =%#",textView1.text);
NSString *String=textView1.text;
DataModel *model = [AuditTextBoxarray objectAtIndex:CurrentIndexPath];
model.AuditTextBoxString = String;
dispatch_async(dispatch_get_main_queue(), ^{
[Audittable reloadData];
});
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
///
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"AuditPost" inManagedObjectContext:context]];
// NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSManagedObject* favoritsGrabbed = [results objectAtIndex:CurrentIndexPath];
[favoritsGrabbed setValue:String forKey:#"warningreason"];
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
else if ([CheckStringShow isEqualToString:#"6"])
{
NSLog(#"Text Value =%#",textView1.text);
NSString *String=textView1.text;
DataModel *model = [AuditTextBoxarray objectAtIndex:CurrentIndexPath];
model.AuditTextBoxString = String;
dispatch_async(dispatch_get_main_queue(), ^{
[Audittable reloadData];
});
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
///
NSManagedObjectContext *context = [self managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"AuditPost" inManagedObjectContext:context]];
// NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
NSManagedObject* favoritsGrabbed = [results objectAtIndex:CurrentIndexPath];
[favoritsGrabbed setValue:String forKey:#"highregion"];
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
}
}

How to delete entries in core data

i am new to core data..
I know how to store and item.
- (void)dbSave:(NSString *)uri withContent:(NSDictionary *)content withExpiry:(double)date {
Cache *cache = [self dbLoad:uri];
if (cache == nil) {
cache = [NSEntityDescription insertNewObjectForEntityForName:#"Cache" inManagedObjectContext:[self managedObjectContext]];
}
double time = (double) [[NSDate date] timeIntervalSince1970] + date;
[cache setLocal:uri];
[cache setTime:#(time)];
NSMutableData *data = [[NSMutableData alloc] init];
NSKeyedArchiver *archiver = [[NSKeyedArchiver alloc] initForWritingWithMutableData:data];
[archiver encodeObject:content forKey:#"data"];
[archiver finishEncoding];
[cache setData:data];
NSError *error;
if (![[self managedObjectContext] save:&error]) {
}
}
But i am stuck with creating a method to clear this core data data base.. Does anyone know how?
NSManagedObjectContext *managedObjectContext=[appDelegate managedObjectContext];
NSFetchRequest *fetchRequest=[NSFetchRequest fetchRequestWithEntityName:#"entity"];
NSArray* currentRecord = [[managedObjectContext executeFetchRequest:fetchRequest error:nil] mutableCopy];
if (currentRecord.count)
{
for (NSManagedObject *obj in currentRecord)
{
[managedObjectContext deleteObject:obj];
}
NSError * error = nil;
if (![managedObjectContext save:&error])
NSLog(#"Can't save ! %# %#",error,[error localizedDescription]);
else
NSLog(#"Data deleted");
}
use this
NSManagedObjectContext *managedContext = [[APP_DELEGATE dbManagerObj] newPrivateContext];
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:#"Cache"];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"isUserData = %#",[NSNumber numberWithBool:true]];
[fetchRequest setPredicate:predicate];
if (IS_IOS9_ANDABOVE) {
NSBatchDeleteRequest *batchDeleteRequest = [[NSBatchDeleteRequest alloc]initWithFetchRequest:fetchRequest];
[[[APP_DELEGATE dbManagerObj]persistentStoreCoordinator]executeRequest:batchDeleteRequest withContext:managedContext error:nil];
}
else
{
NSArray *userRelatedDay = [managedContext executeFetchRequest:fetchRequest error:nil];
for (NSManagedObject *object in userRelatedDay) {
[managedContext deleteObject:object];
}
}

How to update coredata value in Objective-C

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

Getting Null Value From Database NSManagedObject

I am developing iOS app, which fetch data from Web Services and save it to local database and uses it various views as needed. The data is fetch from Web Service and save to database correctly. But while accessing data from NSManagedObject it show FAULT and the consequent NSDictionary shows null Values
The code follows:-
-(void)SaveData:(NSInteger)menuId categoryID:(NSInteger)catID caption:(NSString *)title parentID:(NSInteger)parentID
{
BBAppDelegate *appDelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSManagedObject *userobj = [NSEntityDescription insertNewObjectForEntityForName:tableName
inManagedObjectContext:context];
[userobj setValue:[NSNumber numberWithInt:menuId] forKey:#"id"];
[userobj setValue:[NSNumber numberWithInt:catID] forKey:#"catid"];
[userobj setValue:[NSNumber numberWithInt:parentID] forKey:#"parentid"];
[userobj setValue:title forKey:#"caption"];
NSError *error = nil;
// Save the object to persistent store
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
NSLog(#"app dir: %#",[[[NSFileManager defaultManager] URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask] lastObject]);
}
-(NSArray *)fetchedData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *readData = [[NSFetchRequest alloc] init];
[readData setReturnsObjectsAsFaults:NO];
NSEntityDescription *entity = [NSEntityDescription
entityForName:tableName inManagedObjectContext:context];
[readData setEntity:entity];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:readData error:&error];
// for (Test *test in array)
// {
// NSLog(#"Test: %# ", test.text);
// }
NSLog(#"%#",results);
return results;
}
-(void)removeData{
BBAppDelegate *appdelegate = [[BBAppDelegate alloc]init];
NSManagedObjectContext *context = [appdelegate managedObjectContext];
NSFetchRequest *delData = [[NSFetchRequest alloc]init];
[delData setEntity:[NSEntityDescription entityForName:tableName inManagedObjectContext:context]];
[delData setIncludesPropertyValues:NO];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:delData error:&error];
for (NSManagedObject *value in result) {
[context deleteObject:value];
}
NSError *saveError = nil;
[context save:&saveError];
}
-(void)table:(NSString *)nameTable{
tableName =nameTable;
}
- (instancetype)initWithTableName:(NSString *)tablename
{
[self table:tablename];
return self;
}
-(NSMutableArray *)buldMenu{
NSArray *array = [self fetchedData];
return [self getmenus:0 arr:array];
}
-(NSMutableArray *)getmenus:(NSInteger)parentID arr: (NSArray *)array
{
NSMutableArray *aray = [[NSMutableArray alloc]init];
for (NSManagedObject *dic in array) {
if (dic.faultingState != 0) {
NSLog(#"%lu",(unsigned long)dic.faultingState);
//return nil;
}
NSArray *keys = [[[dic entity] attributesByName] allKeys];
NSLog(#"%#",keys);
NSDictionary *dict = [dic dictionaryWithValuesForKeys:keys];
NSLog(#"%#",dic);
NSLog(#"%#",dict);
NSInteger pID = [[dict objectForKey:#"parentid"]integerValue];
if (pID == parentID) {
BBMenuEntry *entryMenu = [[BBMenuEntry alloc]init];
entryMenu.menuID = [[dict objectForKey:#"id"]integerValue];
entryMenu.catID = [[dict objectForKey:#"catid"]integerValue];
entryMenu.caption = [dict objectForKey:#"caption"];
entryMenu.subMenus = [self getmenus:entryMenu.menuID arr:array];
[aray addObject:entryMenu];
}
}
return aray;
}

Resources