Search code examples
iosobjective-ccore-datansfetchrequestnssortdescriptor

Sorting using NSSortDescriptor by time bug (with core data)


please try to help me here I have some really weird bug(s) trying to sort my string table view objects.

The behaviour is simple, I have:

CreateViewController - here I create strings and add them to core data

StackTableViewController - this is the table view for the strings I create. They should be sorted by date, the first cell is the oldest, the second cell created after him and so on...

HomeViewController - here I have a UILabel that holds the first object of the table view all the time, if I delete it in the table I update this label with a delegate method,

So this is it.

The problem:

If there is NO strings in the table view and then I add a string in the create page, it gets created fine, but if add another one , the new one is at top of the list...but if I terminate the app and open it again the order is fine.

there are also some other weird behaviour after I add more strings...But the thing is, whenever I terminate the app and open it again everything is ordered perfectly..:/

This is the relevant code:

CreateViewController.m

- (id)init { 
    self = [super initWithNibName:@"CreateViewController" bundle:nil];
    if (self) {
    }
    return self;
}


- (void)save {

    if (self.myTextView.text.length == 0) {
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Hey!" message:@"You can't save a blank string" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil, nil];
        [alert show];
    } 

    [self insertTeget];

    [self.presentingViewController dismissViewControllerAnimated:YES completion:nil];

    [self.myTextView resignFirstResponder];
}

//this is where I add the string to the NSManagedObject object I have called 'Target' 
- (void)insertTeget {

    CoreDataStack *stack = [CoreDataStack defaultStack];
    Target *target = [NSEntityDescription insertNewObjectForEntityForName:@"Target" inManagedObjectContext:stack.managedObjectContext];
    if (self.myTextView.text != nil) {
        target.body = self.myTextView.text;
    }

    [stack saveContext];
}

This is the table view:

StackTableViewController.m

- (id)init {

    self = [super initWithNibName:@"StackTableViewController" bundle:nil];
    if (self) {

        [self fetchData];
    }
    return self;
}

//currentTarget is a string I have in the .h file to pass the home view controller the first string of the table view  
- (void)fetchData {
    [self.fetchedResultController performFetch:nil];
    if (self.fetchedResultController.fetchedObjects.count > 0) {
        NSIndexPath *indexPath = [NSIndexPath indexPathForItem:0 inSection:0];
        Target *current = [self.fetchedResultController objectAtIndexPath:indexPath];
        self.currentTarget = current.body;
    }else {
        self.currentTarget = nil;
    }
}

- (void)viewDidLoad {

    [super viewDidLoad];
    [self fetchData];
}

#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return self.fetchedResultController.sections.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    // Return the number of rows in the section.
    id <NSFetchedResultsSectionInfo> sectionInfo = [self.fetchedResultController sections][section];
    return [sectionInfo numberOfObjects];
}

- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return UITableViewCellEditingStyleDelete;
}

//here I'm updating the delegate when A cell was deleted so I can update the label in the home view controller
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {

    Target *target = [self.fetchedResultController objectAtIndexPath:indexPath];
    CoreDataStack *stack = [CoreDataStack defaultStack];
    [[stack managedObjectContext] deleteObject:target] ;
    [stack saveContext];

    if ([_delegate respondsToSelector:@selector(didDeleteObject)]) {
        [self fetchData];
        [_delegate didDeleteObject];
    }
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *cellIdentifier = @"StackTableViewCell";

    Target *target = [self.fetchedResultController objectAtIndexPath:indexPath];

    StackTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier];

    if (!cell)
    {
        NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:@"StackTableViewCell" owner:self options:nil];
        cell = [topLevelObjects objectAtIndex:0];
    }

    cell.cellLabel.text = target.body;

    return cell;
}

// this is my fetch request where im setting up the sort descriptor 
- (NSFetchRequest *)targetsFetchRequest {

    NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Target"];
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"time" ascending:YES];
    NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];
    return fetchRequest;
}


- (NSFetchedResultsController *)fetchedResultController {

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

    CoreDataStack *stack = [CoreDataStack defaultStack];

    NSFetchRequest *fetchRequest = [self targetsFetchRequest];

    _fetchedResultController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:stack.managedObjectContext sectionNameKeyPath:nil cacheName:nil];

    _fetchedResultController.delegate = self;

    return _fetchedResultController;

}

This is the home view controller where Im updating the label:

- (id)init {
    self = [super initWithNibName:@"HomeViewController" bundle:nil];
    if (self) {
        stackTableViewController = [[StackTableViewController alloc] init];
        stackTableViewController.delegate = self;
    }
    return self;
}


- (void)viewWillAppear:(BOOL)animated {
    [stackTableViewController fetchData];
    self.homeLabel.text = stackTableViewController.currentTarget;
}

- (void)viewDidLoad {

    [super viewDidLoad];
    self.homeLabel.text = stackTableViewController.currentTarget;
}

//this is the delegate method
- (void)didDeleteObject { 
    self.homeLabel.text = stackTableViewController.currentTarget;
}

- (IBAction)goToStack:(id)sender {

    [self.navigationController pushViewController:stackTableViewController animated:YES];
}

- (IBAction)goToCreate:(id)sender {

    CreateViewController *createViewController = [[CreateViewController alloc]initWithNibName:@"CreateViewController" bundle:nil];
    UINavigationController *navigationController = [[UINavigationController alloc]initWithRootViewController:createViewController];
    [self.navigationController presentViewController:navigationController animated:YES completion:nil]}

Please please please, it's driving me crazy, why the order is fine only after i terminate the app? thanks@@@!


Solution

  • I don't see you setting time anywhere. It should be set to [NSDate date] when you create the object, if it's acting as a creation date.