I want to call alert view first then go to further NSManagedObject - ios

I am trying to call alert view first then go to NSManagedObject. But when i click on button then it skip alert view and call this at the end of rest code.
Any one know's how can i force this uialertview to load first
Thanks
- (IBAction)confirmOrder:(UIButton *)sender
{
#pragma PopUp Alert Box
_alert = [MLTableAlert tableAlertWithTitle:#"Select Your Table" cancelButtonTitle:nil numberOfRows:^NSInteger (NSInteger section)
{
return 6;
}
andCells:^UITableViewCell* (MLTableAlert *anAlert, NSIndexPath *indexPath)
{
static NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [anAlert.table dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.textLabel.text = [NSString stringWithFormat:#"Table # %d", indexPath.row];
return cell;
}];
[_alert configureSelectionBlock:^(NSIndexPath *selectedIndex){
NSLog(#"Index is = %d", selectedIndex.row);
selectedTable = [NSString stringWithFormat:#"%d",selectedIndex.row];
#pragma Hit Url For New Order
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(#"Got udid from appdelegate = %#",appDelegate.passUdid);
NSString *new_order = [NSString stringWithFormat: #"http://localhost/food/submit_new_order.php?id=NULL&customer_id=%#&table_id=%#&order_datetime=%#&customer_instruction=Normal&estimated_time_min=30-45&actual_time=40&created_on=%#&updated_on=NULL&STATUS=new", appDelegate.passUdid,selectedTable,dateStr,dateStr];
NSString* urlTextEscaped = [new_order stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlTextEscaped];
NSData *myNSData=[NSData dataWithContentsOfURL:url];
} andCompletionBlock:^{
NSLog(#"Cancel Button Pressed\nNo Cells Selected");
}];
_alert.height = 260;
[_alert show];
NSManagedObjectContext *context = [self managedObjectContext];
NSError *error=nil;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"PendingOrder" inManagedObjectContext:context];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [context executeFetchRequest:fetchRequest error:&error];
//e
if (![selectedTable isEqualToString:NULL]) {
for (NSManagedObject *info in fetchedObjects) {
NSMutableString *pDishID = [info valueForKey:#"dishid"];
NSMutableString *pDishQuantity = [info valueForKey:#"quantity"];
NSMutableString *time = [info valueForKey:#"time"];
NSManagedObject *newDevices = [NSEntityDescription insertNewObjectForEntityForName:#"RunningOrder" inManagedObjectContext:context];
[newDevices setValue:pDishID forKey:#"dishid"];
[newDevices setValue:pDishQuantity forKey:#"quantity"];
[newDevices setValue:time forKey:#"time"];
NSLog(#"Getting ID From pending Order = %#",[info valueForKey:#"dishid"]);
#pragma Get Order ID from Order_Main
//s
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSString *ordrMain=#"http://localhost/food/get_order_id.php?id=";
ordrMain = [ordrMain stringByAppendingString:appDelegate.passUdid];
NSURL *urls=[NSURL URLWithString:ordrMain];
NSData *myNSData=[NSData dataWithContentsOfURL:urls];
allItemss = [NSJSONSerialization JSONObjectWithData:myNSData options:kNilOptions error:&error];
NSDictionary *results = [NSJSONSerialization JSONObjectWithData:myNSData options:NSJSONReadingMutableContainers error:nil];
NSString *get_order_id = [[allItemss objectAtIndex:0] objectForKey:#"id"];
NSString *new_order_detail = [NSString stringWithFormat: #"http://localhost/food/order_detail.php?order_id=%#&dish_id=%#&quantity=%#&created_on=%#&updated_on=%#", get_order_id,pDishID,pDishQuantity,dateStr,dateStr];
NSString* urlTextEscaped = [new_order_detail stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
NSURL *url=[NSURL URLWithString:urlTextEscaped];
NSData *myNSDatas=[NSData dataWithContentsOfURL:url];
[context deleteObject:info];
}
if (![context save:&error]) {
NSLog(#"Can't Save! %# %#", error, [error localizedDescription]);
}
}
}

[_alert show] displays the alert window and returns immediately. The "selection block"
is then called when an alert item has been pressed, or the "cancel block" is called
when the Cancel button has been pressed.
Therefore you have to move the code that fetches the managed object into the "selection block":
[_alert configureSelectionBlock:^(NSIndexPath *selectedIndex){
NSLog(#"Index is = %d", selectedIndex.row);
// ...
// Fetch object depending on selectedIndex.
// ...
} andCompletionBlock:^{
NSLog(#"Cancel Button Pressed\nNo Cells Selected");
}];

Related

Some questions about fetch core data

I'm a new guy with iOS, I made an APP and used Core Data.I could save data in Entity,but I can't fetch it.It's worry grammar or other reason.
I want to fetch data and show in TableViewCell
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:SectionsTableIdentifier];
NSFetchRequest *request = [[NSFetchRequest alloc]initWithEntityName:#"Entity"];
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:#"showName" ascending:NO];
request.sortDescriptors = #[sort];
request.fetchLimit = 100;
request.fetchOffset= 0;
NSError *error = nil;
NSArray *array = [self.context executeFetchRequest:request error:&error];
NSMutableDictionary *names = [NSMutableDictionary dictionaryWithCapacity:1];
if(!error){
for (Entity *emp in array ) {
NSLog(#"output:%#",emp.showName);
names =[NSMutableDictionary dictionaryWithObjectsAndKeys:emp.showName, nil];
self.keys =[[self.names allKeys]sortedArrayUsingSelector:#selector(compare:)];
}
}
else{
NSLog(#"%#",error);
}
}
and this is my code with save data
-(IBAction)addButton:(id)sender{
AppDelegate *appDelegate = [UIApplication sharedApplication].delegate;
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSInteger seasonRow = [self.dataPicker selectedRowInComponent:kSeason];
NSInteger episodeRow = [self.dataPicker selectedRowInComponent:kEpisode];
Entity * tvShow1 =[NSEntityDescription insertNewObjectForEntityForName:#"Entity"
inManagedObjectContext:context];
NSError * error = nil;
NSString *name = self.nameField.text;
NSString *introduction = self.introductionField.text;
NSString *dateSeason = self.seasonNumber[seasonRow];
NSString *dateEposide = self.episodeNumber[episodeRow];
NSString *date;
date = [dateSeason stringByAppendingString:dateEposide];
tvShow1.showName =name;
tvShow1.showIntroduction = introduction;
tvShow1.showLastedData = date;
if (!error) {
NSLog(#"保存成功");
NSString *message = [[NSString alloc]initWithFormat:#"你的新剧:%#已经成功添加",name];
UIAlertController *alert=
[UIAlertController alertControllerWithTitle:#"恭喜,添加成功"
message:message
preferredStyle:UIAlertControllerStyleAlert];
UIAlertAction *action = [UIAlertAction actionWithTitle:#"好嘞!"
style:UIAlertActionStyleDefault
handler:nil];
[alert addAction:action];
[self presentViewController:alert animated:YES completion:nil];
[self.contenxt save:&error];
}
[appDelegate saveContext];
}
Thank you very much!

Saving and fetching Multiple Image Selection From Library in Core Data

I am building a project where I am using ELCImagepickerController for multiple selection and then I am saving those selected image into core data. Now I am fetching those images in another VC and showing them into an UICollectionView.
But the problem I am facing here is the images are not properly showing in collectionView. I am having two confusions.
The images are properly saving into core data or not.
If the images are saved, then properly fetching or not.
Here I am entering selected images into core data
- (void)imagePicker:(SNImagePickerNC *)imagePicker didFinishPickingWithMediaInfo:(NSMutableArray *)info
{
_arrImages = [[NSMutableArray alloc]init];
_imgdata = [[NSMutableData alloc]init];
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = app.managedObjectContext;
Albums *objPhotos = (Albums *)[NSEntityDescription insertNewObjectForEntityForName:#"Albums" inManagedObjectContext:context];
//get images
for (int i = 0; i < info.count; i++) {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:info[i] resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
_imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
[objPhotos setPhotosInAlbum:self.imageData];
} failureBlock:^(NSError *error) { }];
}
NSError * err = nil;
[context save:&err];
if (![context save:&err]) {
NSLog(#"Can't Save! %# %#", err, [err localizedDescription]);
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success!!" message:#"Photos Successfully Selected!" delegate:self cancelButtonTitle:#"DONE" otherButtonTitles:nil];
[alert show];
}
Here I am fetching those selected images
-(NSArray *)getMenCategoryList
{
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *moc=app.managedObjectContext;
NSFetchRequest *fetch = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Albums" inManagedObjectContext:moc];
[fetch setEntity:entity];
NSError *error;
NSArray *result = [moc executeFetchRequest:fetch error:&error];
if (!result) {
return nil;
}
return result;
}
I am calling the fetching function in - (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section and returning the array count
- (NSInteger) collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section
{
return [[self getMenCategoryList] count];
}
And lastly, populating the images into collectionView here
- (UICollectionViewCell *) collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath
{
UICollectionViewCell *cell = (UICollectionViewCell *)[collectionView dequeueReusableCellWithReuseIdentifier:#"albumCollectionViewCellCell" forIndexPath:indexPath];
Photos *objAlbumPhotos = (Photos *)[[self getMenCategoryList] objectAtIndex:indexPath.row];
UIImage *albumImg = [UIImage imageWithData:[objAlbumPhotos valueForKey:#"photosInAlbum"]];
UIImageView *photosimageview = (UIImageView *)[cell.contentView viewWithTag:1];
photosimageview.image = albumImg;
return cell;
}
Any help is highly appreciated.
NOTE: i am just edit your code Please confirm first as per your code and edit as per your requirement
step 1: generate Unique file name and save your image with that file name to your file path.
step 2: after successfully write your file then save that path to your core data.
step 3: for fetching use core data path to get images from directory.
- (NSString*)generateFileNameWithExtension:(NSString *)extensionString {
// Extenstion string is like #".png"
NSDate *time = [NSDate date];
NSDateFormatter* df = [NSDateFormatter new];
[df setDateFormat:#"dd-MM-yyyy-hh-mm-ss"];
NSString *timeString = [df stringFromDate:time];
int r = arc4random() % 100;
int d = arc4random() % 100;
NSString *fileName = [NSString stringWithFormat:#"File-%#%d%d%#", timeString, r , d , extensionString ];
NSLog(#"FILE NAME %#", fileName);
return fileName;
}
- (void)imagePicker:(SNImagePickerNC *)imagePicker didFinishPickingWithMediaInfo:(NSMutableArray *)info
{
_arrImages = [[NSMutableArray alloc]init];
_imgdata = [[NSMutableData alloc]init];
AppDelegate* app=(AppDelegate*)[[UIApplication sharedApplication]delegate];
NSManagedObjectContext *context = app.managedObjectContext;
Albums *objPhotos = (Albums *)[NSEntityDescription insertNewObjectForEntityForName:#"Albums" inManagedObjectContext:context];
//get images
for (int i = 0; i < info.count; i++) {
ALAssetsLibrary *assetLibrary=[[ALAssetsLibrary alloc] init];
[assetLibrary assetForURL:info[i] resultBlock:^(ALAsset *asset) {
UIImage *image = [UIImage imageWithCGImage:[asset aspectRatioThumbnail]];
_imageData = [NSData dataWithData:UIImagePNGRepresentation(image)];
NSString *strfilename = [self generateFileNameWithExtension:#".jpg"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:strfilename];
[_imageData writeToFile:filePath atomically:YES];
[objPhotos setPhotosInAlbum:filePath];
} failureBlock:^(NSError *error) { }];
}
NSError * err = nil;
[context save:&err];
if (![context save:&err]) {
NSLog(#"Can't Save! %# %#", err, [err localizedDescription]);
}
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:#"Success!!" message:#"Photos Successfully Selected!" delegate:self cancelButtonTitle:#"DONE" otherButtonTitles:nil];
[alert show];
}

Download data from JSON and store to CoreData and Display in the same time when data downloads in background

I am parsing data from JSON and Storing to CoreData in the same time i am displaying the the data to tableview but the problem i am having is data is displaying only after download completed but i dont want like this i want to download the data in background and display the data while downloading is processed also how can i do this
-(void)connectionDidFinishLoading:(NSURLConnection *)connection
{
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
arrayData = [NSJSONSerialization JSONObjectWithData:data options:0 error:nil];
NSError *error;
NSManagedObjectContext *context = [appDelegate managedObjectContext];
context = [appDelegate managedObjectContext];
for (int i = 0; i < [arrayData count]; i++) {
idNum = [arrayData objectAtIndex:i][#"id"];
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"Discount"];
[request setPredicate:[NSPredicate predicateWithFormat:#"cID = %#",idNum]];
[request setFetchLimit:1];
NSUInteger count = [context countForFetchRequest:request error:&error];
if (count == NSNotFound) {
NSLog(#"ERROR");
}else if (count == 0) {
NSLog(#"New Data Coming");
name = [arrayData objectAtIndex:i][#"name"];
summary = [arrayData objectAtIndex:i][#"summary"];
region = [arrayData objectAtIndex:i][#"region"];
imageURL = [arrayData objectAtIndex:i][#"images"][#"logo"];
id benefits1 = [arrayData objectAtIndex:i][#"benefits"];
benefiteString = [NSString stringWithFormat:#"%# %#",[benefits1 objectAtIndex:0][#"key"],[benefits1 objectAtIndex:0][#"value"]];
NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:imageURL]];
dateUpdate = [arrayData objectAtIndex:i][#"updated_at"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc]init];
[dateFormatter setDateFormat: #"yyyy-MM-dd'T'HH:mm:ss.sssZ"];
NSDate *date =[dateFormatter dateFromString:dateUpdate];
[dateFormatter setDateFormat:#"yyyy/MM/dd HH:mm:ss"];
NSLog(#"DAte : %#",date);
Discount * d = [NSEntityDescription insertNewObjectForEntityForName:#"Discount" inManagedObjectContext:context];
d.name = name;
d.summary = summary;
d.regions = region;
d.cID = idNum;
d.imageLogo = data;
d.updated_at = date;
d.benefits = benefiteString;
if (![context save:&error]) {
NSLog(#"Getting error while saving data");
}
else{
NSLog(#"Saved");
}
}
}
[sharedAppDelegate dismissGlobalHUD];
[listTableView reloadData];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [_myArray count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
customCellClass = [tableView dequeueReusableCellWithIdentifier:#"Cell"];
if (customCellClass == nil)
{
customCellClass = [[CellCustom alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:#"Cell"];
}
customCellClass.nameLabel.text = [[_myArray objectAtIndex:indexPath.row]name];
customCellClass.cityLabel.text =[[_myArray objectAtIndex:indexPath.row]regions];
customCellClass.detailLabel.text = [[_myArray objectAtIndex:indexPath.row]summary];
NSData * d = [[_myArray objectAtIndex:indexPath.row]imageLogo];
customCellClass.mainImage.image = [UIImage imageWithData:d];
customCellClass.benefitsLabel.text = [[_myArray objectAtIndex:indexPath.row]benefits];
[sharedAppDelegate dismissGlobalHUD];
return customCellClass;
}
-(void)dataDidSave
{
NSManagedObjectContext *context = [appDelegate managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Discount" inManagedObjectContext:context]; [fetchRequest setEntity:entity];
[fetchRequest setEntity:entity];
NSError *error = nil;
NSArray *result = [context executeFetchRequest:fetchRequest error:&error];
self.myArray = result;
[listTableView reloadData];
}
-(void)viewWillAppear:(BOOL)animated
{
[sharedAppDelegate showGlobalProgressHUDWithTitle:#"Loading..."];
[self dataDidSave];
}
In connectionDidFinishLoading: try something like this:
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0),^ {
// Process your data and then incrementally call
dispatch_async(dispatch_get_main_queue(),^ {
[listTableView reloadData];
});
}
});

Core data - Data fetching

I am using storyboard and and coredata in my app. In the home screen i want to list all my audio file details and in a button click i want to navigate to another screen and record a new file and save that file in database. When pressing back button i reached to home screen and i want to display the saved audio files in a tableview. Table row count is showing correctly. But the audio details are not correct. But when i stop and rebuild the app it is showing correctly. I wrote the code for reloading the tableview in viewWillApper.
- (void)viewWillAppear:(BOOL)animated
{
[tableview reloadData];
[self loadFiles];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:[NSEntityDescription entityForName:#"AudioDetails" inManagedObjectContext:managedObjectContext]];
[request setIncludesSubentities:NO]; NSError *err;
NSUInteger count = [managedObjectContext countForFetchRequest:request error:&err];
return count;
}
-(UITableViewCell*)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"AudioCell";
AudioCell *cell = (AudioCell *)[tableViewdequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:CellIdentifier owner:self options:nil];
cell = (AudioCell *)[nibArray objectAtIndex:0];
[cell configurePlayerButton];
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"AudioDetails" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
for (NSManagedObject *info in fetchedObjects) {
if(audionames == nil)
audionames = [[NSMutableArray alloc] init];
[audionames addObject:[info valueForKey:#"audioName"]];
//NSManagedObject *details = [info valueForKey:#"details"];
//NSLog(#"Zip: %#", [details valueForKey:#"zip"]);
}
cell.titleLabel.text = [audionames objectAtIndex:indexPath.row];
return cell;
}
- (IBAction)SaveRecordingBtnClicked:(id)sender {
NSString *soundFilePath = [[self getDocumentDirectoryPath]
stringByAppendingPathComponent:OrginalAudioFileName];
NSURL *path=[NSURL URLWithString:soundFilePath];
NSError *error = nil;
AVAudioPlayer* avAudioPlayer = [[AVAudioPlayer alloc]initWithContentsOfURL:path error:&error];
NSManagedObjectContext *context = [self managedObjectContext];
AudioDetails *audioDetails = [NSEntityDescription
insertNewObjectForEntityForName:#"AudioDetails"
inManagedObjectContext:context];
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:soundFilePath error:&error];
NSNumber *fileSizeNumber = [fileAttributes objectForKey:NSFileSize];
NSDate *fileCreationDate = [fileAttributes objectForKey:NSFileCreationDate];
int duration = avAudioPlayer.duration;
[audioDetails setValue:[NSString stringWithFormat:#"%#",OrginalAudioFileName] forKey:#"audioName"];
if (![context save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
}

How to edit the value of some attribute in entity?

How do I edit the value of some field in CoreData entity (SQLite) by tapping to Button?
For example, in my UITableViewCell I have button. I would like this button to change the value of some boolean field. By tapping first time I would like to write YES and second time - NO.
1.Join is a manually created join table Ingredients<->>Join<<->Recipes
2._ingredientInfo contain only 1 record
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cellIngredient";
IngredientCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[IngredientCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
Ingredients *ingredient = [ingredientsArray_ objectAtIndex:indexPath.row];
cell.nameLabel.text = ingredient.name;
//Указываем что-то типа DataSource
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context = appDelegate.managedObjectContext;
if (context != nil) {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"inRecipe == %# AND ingredient == %#", self.recipe, ingredient];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Join" inManagedObjectContext:context];
[request setEntity:entity];
[request setPredicate:predicate];
NSError *error = nil;
NSMutableArray *mutableFetchResult = [[context executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResult == nil) {
NSLog(#"No fetched objects!!!");
abort();
}
_ingredientInfo = [mutableFetchResult objectAtIndex:0];
}
cell.countLabel.text = [NSString stringWithFormat:#"%#", _ingredientInfo.count];
if (_ingredientInfo.inCart == [NSNumber numberWithInt:0]) {
cell.toCartBtn.imageView.image = [UIImage imageNamed:#"runTo.png"];
}
else {
cell.toCartBtn.imageView.image = [UIImage imageNamed:#"inCart.png"];
}
cell.unitLabel.text = ingredient.units;
return cell;
}
and when I tap the button cell.toCartBtn
- (IBAction)toCart:(id)sender
{
if (_ingredientInfo.inCart == [NSNumber numberWithInt:0]) {
_ingredientInfo.inCart = [NSNumber numberWithInt:1];
}
else {
_ingredientInfo.inCart = [NSNumber numberWithInt:0];
}
NSError *error = nil;
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if ([appDelegate.managedObjectContext save:&error]) {
[self.ingredientsTableView reloadData];
}
else {
NSLog(#"Error updating");
}
}
First fetch your object to be modified
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"entityName" inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"(id == %#)", eID]];
NSError *error;
NSArray *details = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
entityName *objEntity= nil;
//error handling goes here
if([details count] > 0)
objEntity = (entityName *)[details objectAtIndex:0];
Now update that entity as you insert it
if(objEntity){
club.fieldName = #"YES";
NSError *error = nil;
if(![self.managedObjectContext save:&error])
NSLog(#"Error updating");
}

Resources