NSPredicate,executeFetchRequest崩溃

时间:2013-12-17 08:20:22

标签: ios objective-c nspredicate nsfetchrequest

我正在做一个核心数据教程而且我一直在崩溃。这是一个objc_exception_throw。

我创建了一个名为loadTableData的方法,并在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];
}

它被困在这里

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

注释掉谓词alloc / init和setPredicate方法调用会导致应用程序崩溃,但不会执行我想要的操作。

请参阅下面的实体和关系。

Core Data Entities

在LabelViewController中,这里有另外的代码来显示如何设置[context objectWithID:self.labelID]

-(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];
}

2 个答案:

答案 0 :(得分:1)

我改为使用CONTAINS

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

你可以使用LIKE,但我喜欢CONTAINS的简洁,请看这个问题: NSPredicate that is the equivalent of SQL's LIKE

答案 1 :(得分:0)

首先,您似乎想要获取“艺术家”对象,而不是“标签”对象:

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

接下来,LIKECONTAINS用于测试字符串,您需要一个简单的==

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

备注:label对象本身传递给推送的视图控制器会更简单, 而不是[label objectID]