Core data - Data fetching - ios

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

Related

general model implementation by Core Data and NSFetchedResultsController

I am newbie in Core Data. I put all model requirements (in respect of MVC) in a class of NSFetchedResultsController as below:
Header File :
#import <CoreData/CoreData.h>
#interface GeneralModel : NSFetchedResultsController
#property (nonatomic, strong) NSManagedObjectContext *context;
#property (nonatomic, strong) NSManagedObjectModel *model;
- (NSString *)storagePath;
- (void)removeStorage;
- (void)truncateAllEntity;
- (void)truncateEntity:(NSString *)entityName;
- (void)addGroups:(NSDictionary *)insertData;
- (NSArray *)getEntity:(NSString *)entityName sortBy:(NSString *)sortAttribute;
- (id)getMaxValue:(NSString *)entityName forProperty:(NSString *)propertyName;
- (NSArray *)getEntity:(NSString *)entityName predicateBy:(NSPredicate *)predicate sortBy:( NSString * )sortAttribute;
#end
Main File:
#import "GeneralModel.h"
#import "GeneralHelper.h"
#implementation GeneralModel
- (instancetype)init
{
self = [super init];
if (self) {
// Read in Model.xcdatamodeld
_model = [NSManagedObjectModel mergedModelFromBundles:nil];
NSPersistentStoreCoordinator *psc =
[[NSPersistentStoreCoordinator alloc] initWithManagedObjectModel:_model];
// Where does the SQLite file go?
NSString *path = self.storagePath;
NSURL *storeURL = [NSURL fileURLWithPath:path];
NSError *error = nil;
if (![psc addPersistentStoreWithType:NSSQLiteStoreType
configuration:nil
URL:storeURL
options:nil
error:&error]) {
#throw [NSException exceptionWithName:#"OpenFailure"
reason:[error localizedDescription]
userInfo:nil];
}
// Create the managed object context
_context = [[NSManagedObjectContext alloc] init];
_context.persistentStoreCoordinator = psc;
}
return self;
}
- (NSString *)storagePath
{
NSArray *documentDirectories =
NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask,
YES);
// Get one and only document directory from that list
NSString *documentDirectory = [documentDirectories firstObject];
return [documentDirectory stringByAppendingPathComponent:#"model.sqlite"];
}
- (void)removeStorage {
// NSError *error2;
// NSString *storagePath = [self storagePath];
//
// NSDictionary *options = #{NSPersistentStoreUbiquitousContentNameKey: #"model"};
// bool removeResult = [NSPersistentStoreCoordinator removeUbiquitousContentAndPersistentStoreAtURL:[NSURL URLWithString:storagePath] options:options error:&error2];
// if (removeResult == NO) {
// NSLog(#"Could not remove Storage. Reason: %#", error2.localizedFailureReason);
// }
NSPersistentStore *store = [self.context.persistentStoreCoordinator.persistentStores lastObject];
NSError *error = nil;
NSURL *storeURL = store.URL;
BOOL isRemovePersistentStore = [self.context.persistentStoreCoordinator removePersistentStore:store error:&error];
if (isRemovePersistentStore == NO) {
NSLog(#"NO RemovePersistentStore. Reason: %#", error.localizedFailureReason);
}
BOOL isRemoveItemAtURL = [[NSFileManager defaultManager] removeItemAtURL:storeURL error:&error];
if (isRemoveItemAtURL == NO) {
NSLog(#"NO RemoveItemAtURL. Reason: %#", error.localizedFailureReason);
}
}
- (void)truncateAllEntity {
NSArray *entities = self.model.entities;
for (NSEntityDescription *entityDescription in entities) {
[self truncateEntity:entityDescription.name];
}
}
- (void)truncateEntity:(NSString *)entityName {
// delete all database
if (IOS_VERSION >= 9) {
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:entityName];
NSBatchDeleteRequest *delete = [[NSBatchDeleteRequest alloc] initWithFetchRequest:request];
NSError *deleteError = nil;
[self.context.persistentStoreCoordinator executeRequest:delete withContext:self.context error:&deleteError];
} else {
NSFetchRequest *allItems = [[NSFetchRequest alloc] init];
[allItems setEntity:[NSEntityDescription entityForName:entityName inManagedObjectContext:self.context]];
[allItems setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSError *error = nil;
NSArray *items = [self.context executeFetchRequest:allItems error:&error];
//error handling goes here
for (NSManagedObject *item in items) {
[self.context deleteObject:item];
}
NSError *saveError = nil;
[self.context save:&saveError];
//more error handling here
}
[self.context rollback];
}
- (void)addGroups:(NSDictionary *)insertData {
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"yyyy-MM-dd HH:mm:ss"];
for (NSDictionary *response in insertData) {
NSManagedObject *existingGroup = [self getEntity:#"Group" AtValue:response[#"groupId"] forProperty:#"group_id" ];
if (existingGroup) {
NSLog(#"existingGroup");
continue;
}
// for (int i; i<=20; i++) {
// set bullet
NSManagedObject *object_bullet = [NSEntityDescription insertNewObjectForEntityForName:#"Group_bullet"
inManagedObjectContext:self.context];
NSData *bulletData = [[NSData alloc] initWithBase64EncodedString:response[#"bullet"] options:NSDataBase64DecodingIgnoreUnknownCharacters];
[object_bullet setValue:bulletData forKey:#"bullet"];
[object_bullet setValue:response[#"groupId"] forKey:#"group_id"];
// set group
NSManagedObject *object = [NSEntityDescription insertNewObjectForEntityForName:#"Group"
inManagedObjectContext:self.context];
[object setValue:object_bullet forKey:#"relatedBullet"];
// NSDate *createDate = [dateFormatter dateFromString:response[#"createDate"]];
// [object setValue:createDate forKey:#"group_created_date"];
NSNumber *createDate = response[#"createDate"];
[object setValue:[NSDate dateWithTimeIntervalSince1970:[createDate doubleValue]] forKey:#"group_created_date"];
[object setValue:response[#"groupId"] forKey:#"group_id"];
[object setValue:[GeneralHelper getInteger:response[#"memberNumber"]] forKey:#"group_members_count"];
[object setValue:response[#"name"] forKey:#"group_name"];
[object setValue:[GeneralHelper getInteger:response[#"privacy"]] forKey:#"group_privacy"];
[object setValue:#1 forKey:#"group_status"];
[object setValue:response[#"imageName"] forKey:#"image_name"];
[object setValue:response[#"lastMessageId"] forKey:#"last_message_id"];
[object setValue:response[#"lastMessageText"] forKey:#"last_message_text"];
//
// NSDate *lastMessageDate = [dateFormatter dateFromString:response[#"lastMessageDate"]];
// [object setValue:lastMessageDate forKey:#"last_time"];
NSNumber *lastMessageDate = response[#"lastMessageDate"];
[object setValue:[NSDate dateWithTimeIntervalSince1970:[lastMessageDate doubleValue]] forKey:#"last_time"];
[object setValue:response[#"machineId"] forKey:#"machine_id"];
NSNumber *timestamp = response[#"timestamp"];
[object setValue:[NSDate dateWithTimeIntervalSince1970:[timestamp doubleValue]] forKey:#"timestamp"];
[object setValue:[GeneralHelper getInteger:response[#"unreadCount"]] forKey:#"unread_count"];
// }
}
NSError *errorInsert;
if (![self.context save:&errorInsert]) {
NSLog(#"Failed to save - error: %#", [errorInsert localizedDescription]);
}
[self.context rollback];
}
- (id)getMaxValue:(NSString *)entityName forProperty:(NSString *)propertyName {
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:entityName];
fetchRequest.fetchLimit = 1;
fetchRequest.sortDescriptors = #[[NSSortDescriptor sortDescriptorWithKey:propertyName ascending:NO]];
NSError *error = nil;
id maxValue = [self.context executeFetchRequest:fetchRequest error:&error].firstObject;
if (maxValue == nil) {
maxValue = #{propertyName : #0};
}
[self.context rollback];
return [maxValue valueForKey:propertyName];
}
- (id)getEntity:(NSString *)entityName AtValue:(NSString *)indexValue forProperty:(NSString *)propertyName {
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:entityName inManagedObjectContext:self.context];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"%K == %#", propertyName, indexValue];
// NSLog(#"predicate: %#", predicate);
[request setEntity:entity];
[request setPredicate:predicate];
[request setFetchLimit:1];
NSError *error;
NSArray *results = [self.context executeFetchRequest:request error:&error];
NSManagedObject *object = [results firstObject];
// if (object) {
// // there is at least one object matching you predicate
// } else {
// // there is no object matching your predicate in the moc
// }
// NSLog(#"results member %#", results);
// [self.context rollback];
return object;
}
Then I use this general model in my UITableViewController.
Is there any better way to do this? Or my implementation is buggy and useless?
It think this is a nice approach, but it has some drawbacks.
An NSFetchedResultsController is responsible, as the name implies for controlling results that were fetched. If you add functionality like deleting and modifying things, you are making an object with too many responsibilities.
Imagine there is one viewController showing results in a tableview. It would only need the fetchedresultscontroller functionality, nothing more. If by tapping on a cell you go into a new view controller where edits are possible, you don't need a fetchedresultscontroller: you need a managedObject to edit. This editViewController could use a child context of the tableViewController so that on cancel, all edits are discarded by simply discarding the child context.
I would suggest to no subclass the NSFetchedResultsController, but instead implement a subclass of NSObject that you initialize with an NSNMagedObjectContext that can do the things that apply to the entire context. Like adding groups, removing all data etc.
Then use composition: this NSObject subclass can be a property of a viewController so the viewCOntroller has a way to do those things without having this operation being specific to this viewController.
In general, instead of subclassing, consider composition first. This is because transforming a small components of a composed object to an object that is a certain subclass is usually easier then the other way around.
Feel free to disagree :), but this is what I've learned from experience of working with many people for a long time on a very large codebase.

How to delete particular user's chat from XMPP server in iOS?

I am new in iPhone Application Development. I am working on chat app in iOS using XMPP and Ejabberd. But I am not able to delete the chat of particular user (not a single message).
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
[self DeleteMessageChat:indexPath];
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[messages removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath]
withRowAnimation:UITableViewRowAnimationFade];
}
}
-(void)DeleteMessageChat :(NSIndexPath *)indexpath
{
self.cls=[self.arrProfile objectAtIndex:indexpath.row];
NSString *userJid = [NSString stringWithFormat:#"%#%#",self.cls.UserId,Xmppserver];
XMPPMessageArchivingCoreDataStorage *storage = appDelegate.xmppMessageArchivingStorage;
NSManagedObjectContext *moc = [storage mainThreadManagedObjectContext];
NSEntityDescription *entityDescription = [NSEntityDescription entityForName:#"XMPPMessageArchiving_Message_CoreDataObject"
inManagedObjectContext:moc];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
[request setEntity:entityDescription];
NSString *predicateFrmt = #"bareJidStr == %#";
NSError *error;
NSPredicate *predicate = [NSPredicate predicateWithFormat:predicateFrmt, userJid];
request.predicate = predicate;
NSArray *messages_new = [moc executeFetchRequest:request error:&error];
NSManagedObject *obj=[messages_new objectAtIndex:indexpath.row];
[moc deleteObject:obj];
error = nil;
if (![moc save:&error])
{
NSLog(#"Error deleting movie, %#", [error userInfo]);
}
}
Please help me to solved this problem.
I did this in my code. Try to edit according to you arrays.
NSString *userJid = [NSString stringWithFormat:#"%#%#",cell.frndName.text,DomainName];
NSString *userJid1= [NSString stringWithFormat:#"%#%#",[[NSUserDefaults standardUserDefaults]valueForKey:#"name"],DomainName];
NSFetchRequest *messagesCoreD = [[NSFetchRequest alloc] init];
NSManagedObjectContext *context=[[self appDelegate].xmppMessageArchivingCoreDataStorage mainThreadManagedObjectContext];
NSEntityDescription *messageEntity = [NSEntityDescription entityForName:#"XMPPMessageArchiving_Contact_CoreDataObject" inManagedObjectContext:context];
[messagesCoreD setEntity:messageEntity];
[messagesCoreD setIncludesPropertyValues:NO]; //only fetch the managedObjectID
NSString *predicateFrmt = #"bareJidStr == %#";
NSString *predicateFrmt1 = #"streamBareJidStr == %#";
NSPredicate *predicateName = [NSPredicate predicateWithFormat:predicateFrmt,userJid];
NSPredicate *predicateSSID = [NSPredicate predicateWithFormat:predicateFrmt1,userJid1];
NSArray *subPredicates = [NSArray arrayWithObjects:predicateName, predicateSSID, nil];
NSPredicate *orPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:subPredicates];
messagesCoreD.predicate = orPredicate;
NSError * error = nil;
NSArray * messages = [context executeFetchRequest:messagesCoreD error:&error];
//error handling goes here
[tableView reloadData];
for (NSManagedObject * message in messages)
{
[context deleteObject:message];
[tableView reloadData];
}
NSEntityDescription *messageEntity1 = [NSEntityDescription entityForName:#"XMPPMessageArchiving_Message_CoreDataObject" inManagedObjectContext:context];
[messagesCoreD setEntity:messageEntity1];
[messagesCoreD setIncludesPropertyValues:NO]; //only fetch the managedObjectID
messagesCoreD.predicate = orPredicate;
NSArray * messages1 = [context executeFetchRequest:messagesCoreD error:&error];
//error handling goes here
[tableView reloadData];
for (NSManagedObject * message in messages1)
{
[context deleteObject:message];
[tableView reloadData];
}
NSError *saveError = nil;
[context save:&saveError];
I added this code in commitEditingStyle delegate method. Here you pass friend name in userJid and logged in user name in userJid1.

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

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

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

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