2015-04-06 178 views
0

我有两个实体模型“Content”和“LessonsContent”,它们之间没有任何关系。两个实体都具有NSNumber类型的共同属性“contentID”。我从给定谓词的“内容”实体中提取所有内容对象,并将这些对象存储在内容数组中。我成功地这样做了。 现在,我想从内容数组中存在contentIds的“LessonsContent”实体中提取所有LessonContent对象。子查询谓词核心数据

我使用下面的代码:

NSPredicate * predicate = [NSPredicate predicateWithFormat:@"(contentType == %@)", @"Games"]; 


    NSError * error; 
    NSFetchRequest * request = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([Content class])]; 
    [request setPredicate:predicate]; 
    [request setReturnsObjectsAsFaults:NO]; 
    NSArray *contents = [[DELEGATE managedObjectContext] executeFetchRequest:request error:&error]; 

    if(error){ NSLog(@"Error in fatching data");} 


    //predicate = [NSPredicate predicateWithFormat:@"Content.contentID IN %@", contents]; 

    predicate = [NSPredicate predicateWithFormat:@"(SUBQUERY(contents, $x, $x.Content.contentID IN %@)[email protected] != 0)",contents]; 

    request = [[NSFetchRequest alloc] initWithEntityName:NSStringFromClass([LessonsContent class])]; 
    [request setPredicate:predicate]; 
    NSArray * mappingArray = [[DELEGATE managedObjectContext] executeFetchRequest:request error:&error]; 
    NSLog(@"mappingArray %@", mappingArray); 

但应用程序崩溃。请提出适当的解决方案 在此先感谢。

+0

对第二个谓词使用IN子句。 [计算器] [1] [1]:http://stackoverflow.com/questions/6130900/filter-core-data-results-by-property-in-array – 2015-04-06 10:32:12

+0

内容识别属性是NSNumber类型。我已经尝试过,但它不起作用。 – 2015-04-06 10:36:39

+0

我会考虑使用'NSCompoundPredicate'和便捷方法'andPredicateUsingSubpredicates:'see [here](https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/NSCompoundPredicate_Class/) – andrewbuilder 2015-04-07 08:10:10

回答

0

你必须得到一个contentID数组的第一个。然后使用IN。

NSArray *contents = [[DELEGATE managedObjectContext] executeFetchRequest:request error:&error]; 

NSArray * allContentIDs = [contents valueForKey:@"contentID"]; 

然后用第二个谓语

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"contentID IN %@", allContentIDs]; 

[request setPredicate:predicate]; 

希望这有助于。