Question

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];
}
Was it helpful?

Solution 2

First of all, it seems that you want to fetch "Artist" objects, not "Label" objects:

NSEntityDescription *entity = [NSEntityDescription entityForName:@"Artist" inManagedObjectContext:context];

Next, LIKE or CONTAINS are for testings strings, you need a simple ==:

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

Remark: It would be simpler to pass the label object itself to the pushed view controller, instead of [label objectID].

OTHER TIPS

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

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