Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSPredicate, executeFetchRequest crash

I'm doing a Core Data tutorial and I keep getting a crash. It's a objc_exception_throw.

I create a method called loadTableData and call it in viewDidLoad

-(void)loadTableData{
    NSManagedObjectContext *context = [[self appDelegate]managedObjectContext];
    NSFetchRequest *fetchRequest = [[NSFetchRequest alloc]init];
    NSEntityDescription *entity = [NSEntityDescription entityForName:@"Label" inManagedObjectContext:context];

    [fetchRequest setEntity:entity];

    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"label like %@", [context objectWithID: self.labelID]];

    [fetchRequest setPredicate:predicate];


    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc]initWithKey:@"name" ascending:YES];

    NSArray *sortDescriptors = [[NSArray alloc]initWithObjects:sortDescriptor, nil];
    [fetchRequest setSortDescriptors:sortDescriptors];

    NSError *error = nil;
    self.artistArray = [context executeFetchRequest:fetchRequest error:&error];

    [self.tableView reloadData];
}

It gets stuck here

self.artistArray = [context executeFetchRequest:fetchRequest error:&error];

Commenting out the predicate alloc/init and setPredicate method call results in an app that doesn't crash, but doesn't do what I want.

See entities and relationships below.

Core Data Entities

In LabelViewController here is additional code to show how [context objectWithID: self.labelID] is set

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    MLBLArtistViewController *artistViewController = [self.storyboard instantiateViewControllerWithIdentifier:@"ArtistViewController"];

    Label *label = [self.labelArray objectAtIndex:indexPath.row];

    artistViewController.labelID = [label objectID];

    [self.navigationController pushViewController:artistViewController animated:YES];
}
like image 578
noobsmcgoobs Avatar asked Jan 27 '26 21:01

noobsmcgoobs


1 Answers

I'd use a CONTAINS instead:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"label CONTAINS[cd] %@", [context objectWithID: self.labelID]];

You can use a LIKE but I like the simplicity of the CONTAINS, see this quesiton: NSPredicate that is the equivalent of SQL's LIKE

like image 153
Slee Avatar answered Jan 29 '26 10:01

Slee



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!