Question

I'm using NSFetchedResultController among with core data in my app.But NSFetchedResultController delegate methods not get called when i insert new record, however it works when i attempt to delete or update existing records.Here is my code -

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.


    //fetch friends from DB
    AppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
    self.managedObjectContext = appDelegate.managedObjectContext;

    NSError *error;
    if (![[self fetchedResultsController] performFetch:&error]) {
        // Update to handle the error appropriately.
        NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
        exit(-1);  // Fail
    }
}

- (NSFetchedResultsController *)fetchedResultsController {

    if (_fetchedResultsController != nil) {
        return _fetchedResultsController;
    }

    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
    NSEntityDescription *entity = [NSEntityDescription
                                   entityForName:@"Friends" inManagedObjectContext:self.managedObjectContext];
    [fetchRequest setEntity:entity];

    [fetchRequest setFetchBatchSize:20];

    NSPredicate *predicate = [NSPredicate predicateWithFormat: @"status == 0"];
    [fetchRequest setPredicate:predicate];

    NSSortDescriptor *sort = [[NSSortDescriptor alloc]
                              initWithKey:@"userId" ascending:NO];
    [fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];

    NSFetchedResultsController *theFetchedResultsController =
    [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
                                        managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil
                                                   cacheName:@"Root"];
    self.fetchedResultsController = theFetchedResultsController;
    _fetchedResultsController.delegate = self;

    return _fetchedResultsController;

}

and this for save/update/delete -

-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{

    if (alertView.tag == 1001) {

        if (buttonIndex == 0) { // add new friend

            NSString* fid = [[alertView textFieldAtIndex:0].text stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
            if (fid.length == 0) {

                [AppDelegate showInfoAlert:@"Please enter friends's ID."];
                return;
            }
            NSString* userid = [[NSUserDefaults standardUserDefaults] valueForKey:@"userId"];

            NSString* req = [JSONCreator getAddFriendEnc:myId andFid:fid];

            if ([fid isEqualToString:userid]) {

                [AppDelegate showInfoAlert:@"Please enter your friends's ID."];
                return;
            }
            [ConnectionManager invokeAsync:@"GET" body:req request:@"/friends" viewForHud:self.view completion:^(NSDictionary* res, NSString* error){

                if (error) {

                    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:error delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:Nil, nil];
                    [alert show];
                }
                else
                {

                    Friends * newEntry = [NSEntityDescription insertNewObjectForEntityForName:@"Friends" inManagedObjectContext:managedObjectContext];
                    newEntry.userId = userid;
                    newEntry.friendId = fid;
                    newEntry.status = @"0";

                    NSError *error;
                    if (![managedObjectContext save:&error]) {
                        NSLog(@"Whoops, couldn't save: %@", [error localizedDescription]);
                    }
                    //[managedObjectContext insertObject:newEntry];
                    //[self.frindsTable reloadData];
                    UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Success!" message:[res valueForKey:@"response"] delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:Nil, nil];
                    [alert show];
                }
            }];
        }
    }
    else if (alertView.tag == 1002){ // delete friend

        NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:selectedIndexPath];
        [managedObjectContext deleteObject:managedObject];
        [managedObjectContext save:nil];
       [NSFetchedResultsController deleteCacheWithName:nil];

        UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Friend removed from your friend list." delegate:Nil cancelButtonTitle:@"Ok" otherButtonTitles:Nil, nil];
        [alert show];
    }
    else if (alertView.tag == 1003){ // update friend


        NSString* req = [JSONCreator getBlockFriendEnc:myId andFid:frndtoBlock];

        [ConnectionManager invokeAsync:@"GET" body:req request:@"/friends" viewForHud:self.view completion:^(NSDictionary* res, NSString* error){

            if (error) {

                UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"Error!" message:error delegate:Nil cancelButtonTitle:@"OK" otherButtonTitles:Nil, nil];
                [alert show];
            }
            else
            {
                NSString* userid = [[NSUserDefaults standardUserDefaults] valueForKey:@"userId"];
                Friends* newFriend;
                NSError * error;
                NSFetchRequest * fetchRequest = [[NSFetchRequest alloc] init];
                [fetchRequest setEntity:[NSEntityDescription entityForName:@"Friends"
                                                    inManagedObjectContext:managedObjectContext]];
                [fetchRequest setFetchLimit:1];

                [fetchRequest setPredicate:[NSPredicate predicateWithFormat:@"(userId == %@) && (friendId == %@)",userid, frndtoBlock]];

                if ([managedObjectContext countForFetchRequest:fetchRequest error:&error])
                    newFriend = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] lastObject];

                newFriend.status = @"1";


                // save
                if (! [managedObjectContext save:&error])
                    NSLog(@"Couldn't save data to %@", NSStringFromClass([self class]));

                [NSFetchedResultsController deleteCacheWithName:nil];

                UIAlertView * alert = [[UIAlertView alloc] initWithTitle:@"Success!" message:@"Friend blocked from your friend list." delegate:Nil cancelButtonTitle:@"Ok" otherButtonTitles:Nil, nil];
                [alert show];
            }
        }];

    }

}

Data is saved to data base but table view not reloaded.what i'm doing wrong? Any suggestion would be appreciated.

Was it helpful?

Solution

I guess the problem is

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"status == 0"];

change this with

NSPredicate *predicate = [NSPredicate predicateWithFormat: @"status == '0'"];

hope this will help..

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top