0

I am new to this coredata. Just to be familiar with relationship i created two entities CategoryList (consists of attribute 'categories') and ExpenseList(consists of attribute 'amountspent') which has a to many relationship. Relationship from 'CategoryList' To 'ExpenseList' is 'expenselist'. The 1st tableview shows the total expense in each categories like

food              -150  
transportation    -100  
mobile            -100  
shopping          -500    

and the second tableview shows individual expenses like

food              -100  
food              -50  
transportation    -100  
mobile            -50  
mobile            -50  
shopping          -200  
shopping          -100  
shopping          -200  

I have written the codes to delete an individual expense row from my second tableview using object id since its threadsafe. When i delete a food entry from my second table view say

food              -50

and when i navigate back to 1st tableview it should update food and show

food               -100

I have registered the first tableview with default notification center and first table view is sending notification (checked by nslog) whenever an object is deleted. When first tableview receives a notification it reloads the data in the tableview. But while reloading the tableview is showing undesired value for the category whose object is deleted from the next tableview. Both tableviews are connected by navigation controller.

Here is my m.file for the 1st tableview.

#import "displayTable.h"
#import "CategoryList.h"
#import "ExpenseList.h"
#import "IncomeList.h"
#import "coreAppDelegate.h"
@interface displayTable ()

@end

@implementation displayTable
- (NSManagedObjectContext *)managedObjectContext
{
    NSManagedObjectContext *context = nil;
    id delegate = [[UIApplication sharedApplication] delegate];
    if ([delegate performSelector:@selector(managedObjectContext)]) {
        context = [delegate managedObjectContext];
    }
    return context;
}
- (id)initWithStyle:(UITableViewStyle)style
{
   self = [super initWithStyle:style];
   if (self) {
    // Custom initialization
   }
   return self;
}
- (void)viewDidLoad
{
   [super viewDidLoad];
   todaysL = [[todayslist alloc]init];
   self.expenseArray = [[NSMutableArray alloc] 
                       initWithObjects:@"0.00",
                                       @"0.00",
                                       @"0.00",
                                       @"0.00",
                                       @"0.00",
                                       @"0.00", 
                                       nil];
  self.categoryArray = [[NSMutableArray alloc] 
                    initWithObjects:@"food",
                                    @"transportation",
                                    @"fuel",
                                    @"mobile",
                                    @"shopping", 
                                    @"others", 
                                    nil];
  [self populateExpenses];  
  NSOperationQueue *mainQueue = [NSOperationQueue mainQueue];   
  [[NSNotificationCenter defaultCenter]          
      addObserverForName:NSManagedObjectContextObjectsDidChangeNotification 
                  object:nil 
                   queue:[NSOperationQueue mainQueue] 
              usingBlock:^(NSNotification *notification)
              {
                  NSLog(@"Notification received!");
                  [self populateExpenses];
                  //   [self viewDidLoad];
                  [self.tableView reloadData];
              }];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.

// self.navigationItem.rightBarButtonItem = self.editButtonItem;

}
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];   
}
- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}  

#pragma mark-Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
   //#warning Potentially incomplete method implementation.
   // Return the number of sections.
   return 1;

}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
   //#warning Incomplete method implementation.
   // Return the number of rows in the section.
   return [self.categoryArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
   static NSString *CellIdentifier = @"Cell";
   UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier forIndexPath:indexPath];
  // Configure the cell...

   if(cell == nil)
   {
       cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle
                                     reuseIdentifier:CellIdentifier];
   }
   cell.textLabel.text = [_categoryArray objectAtIndex:indexPath.row];
   cell.detailTextLabel.text = [_expenseArray objectAtIndex:indexPath.row];
   return cell;
}

this is my function for fetching data

-(void)populateExpenses
{

    NSManagedObjectContext *managedObjectContexts = [self managedObjectContext];
    NSEntityDescription *categorylistEntity = [NSEntityDescription entityForName:@"CategoryList" inManagedObjectContext:managedObjectContext];
    NSFetchRequest *request = [[NSFetchRequest alloc]init];
    [request setEntity:categorylistEntity];
    NSError *error =nil;
    NSArray *fetchedObjects = [managedObjectContext executeFetchRequest:request error:&error];
    if(fetchedObjects == nil)
    {
        NSLog(@"your fetching cause error");
    }
    else
    {
        for(CategoryList *categoryL in fetchedObjects)
        {
            if([categoryL.categories isEqualToString: @"food"] )
            {
                for(ExpenseList *expenseL in categoryL.expenselist)
                {
                    food = food + expenseL.amountSpent;
                    //NSLog(@"display food %f",food);                       
                }
                NSString *foodString = [NSString stringWithFormat:@"%.2f",food];
                [self.expenseArray replaceObjectAtIndex:0 withObject:foodString];
                //NSLog(@"foooood%f",food);
            }
            else if ([categoryL.categories isEqualToString: @"transportation"])
            {
                for(ExpenseList *expenseL in categoryL.expenselist)
                {
                    transportation = transportation + expenseL.amountSpent;
                }
                NSString *transportationString = [NSString stringWithFormat:@"%.2f",transportation];
                [self.expenseArray replaceObjectAtIndex:1 withObject:transportationString];
            }
            else if ([categoryL.categories isEqualToString: @"fuel"])
            {
                for(ExpenseList *expenseL in categoryL.expenselist)
                {
                    fuel = fuel + expenseL.amountSpent;
                }
                NSString *fuelString = [NSString stringWithFormat:@"%.2f",fuel];
                [self.expenseArray replaceObjectAtIndex:2 withObject:fuelString];
            }
            else if([categoryL.categories isEqualToString: @"mobile"])
            {
                for(ExpenseList *expenseL in categoryL.expenselist)
                {
                    mobile = mobile + expenseL.amountSpent;
                }
                NSString *mobileString = [NSString stringWithFormat:@"%.2f",mobile];
                [self.expenseArray replaceObjectAtIndex:3 withObject:mobileString];
            }
            else if([categoryL.categories isEqualToString: @"shopping"])
            {
                for(ExpenseList *expenseL in categoryL.expenselist)
                {
                    shopping = shopping + expenseL.amountSpent;
                }
                NSString *shoppingString = [NSString stringWithFormat:@"%.2f",shopping];
                [self.expenseArray replaceObjectAtIndex:4 withObject:shoppingString];
            }
            else if ([categoryL.categories isEqualToString:@"others"])
                for(ExpenseList *expenseL in categoryL.expenselist)
                {
                    others = others + expenseL.amountSpent;
                }
                NSString *othersString = [NSString stringWithFormat:@"%.2f",others];
                [self.expenseArray replaceObjectAtIndex:5 withObject:othersString];
            NSLog(@"%@",othersString);
            }
        //NSLog(@"count %d", self.expenseArray.count);
    }
 }
 /*

// Override to support conditional editing of the table view.

- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
*/

/*
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
    // Delete the row from the data source
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}   
else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view
}   
}
*/

 /*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}

*/

/*

// Override to support conditional rearranging of the table view.

- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
    return YES;
}

*/

#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
 <#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:@"<#Nib name#>" bundle:nil];

 // ...

 // Pass the selected object to the new view controller.

 [self.navigationController pushViewController:detailViewController animated:YES];

 */
}
@end

but when i quit and restart my app everything is updated as it is supposed to be, but not updating immediately after deleting. I could not figure it why. Also i don't know whether this is the right way of doing things with coredata. If anyone could guide me, Thanks in advance

2 Answers 2

0

Yes, you're missing some of the core concepts of core data, which means you're doing a lot more work than you need to.

You have the names of the top level categories in the database, but you don't know what order you're going to get them in, so you create a separate array and do a bunch of complex stuff to get the values from the database in the same order. Much better to just add a 'displayOrder' field to the database and add an order by field to the fetch.

Get rid of your categoryArray property completely and in your populateExpenses function, just do the fetch ( with a sort clause). Save the fetchedObjects to an array property.

You need to do a fetch to get your top level objects in the first place, but once you have them, it is rare that you need to do more fetches.

In your cellForRowAtIndexPath:

CategoryList* category = [_fetchedObjects objecatAtIndex:indexPath.row]; cell.textLabel.text = category.categories; cell.detailTextLabel.text = [[category valueForKeyPath:@"[email protected]"] description];

You don't need to pre-fetch this, you can do this at the time you display the data.

Updating the objects to ensure your changes are taken notice of :-

for ( NSManagedObject* object in self.categoryArray) {
    [self.managedObjectContext refreshObject: object mergeChanges:YES];
}

What this does, most of the time, is tell the object that it needs to re-update it's values next time they are requested.

Hope this helps.

3
  • I tried that code and when I run, my app crashes showing message: this class is not key value coding-compliant for the key expenselist.'
    – Arun Kumar
    Commented May 18, 2013 at 6:37
  • OK, I can see that, I was being a little too general, I'll edit the answer Commented May 18, 2013 at 16:29
  • Thanks a lot, I will let you know after trying this
    – Arun Kumar
    Commented May 19, 2013 at 6:07
0

i got it solved by just clearing the float variables values after storing it in the array. since i was not clearing float variables before, while reloading the table view the previous values in the float variables also get added once again thereby giving undesired values. so in the viewWillAppear method i wrote reload table view and cleared float variables contents and it worked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.