我有一个非常简单的获取请求,我想执行它。我的一个实体有一个名为 smartCollectionIds 的属性,它是可转换的类型。我使用这个属性来存储一个NSArray
简单的字符串。在我的代码中,我使用 anNSfetchedResultsController
来填充表格视图。im 使用的谓词如下:
predicate=[NSPredicate predicateWithFormat:@"smartCollectionIds!=nil && (%@ IN smartCollectionIds)",@"87F173A5-863D-4ECE-9673-A61D8F1E01FC-6285-000009A9CBAF3290"];
但是,这会导致崩溃,特别是在我执行提取时。但是,如果我首先使用 fetch 将我的所有对象加载到一个数组中,然后使用上述谓词将它们过滤掉,则应用程序不会崩溃,并且我会得到预期的结果。所以基本上 下面的这段代码不起作用
-(void) tryTO
{
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Tweetary" inManagedObjectContext: [[ChubbyEyetwitterEngine sharedInstance] getManagedObjectContextForUse]];
NSPredicate *predicate;
predicate=[NSPredicate predicateWithFormat:@"smartCollectionIds!=nil && (%@ IN smartCollectionIds)",@"87F173A5-863D-4ECE-9673-A61D8F1E01FC-6285-000009A9CBAF3290"];
NSSortDescriptor *secondarySortKey = [[[NSSortDescriptor alloc] initWithKey:@"created_at" ascending:FALSE] autorelease];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease] ;
[request setEntity:entity];
[request setPredicate:predicate];
[request setSortDescriptors:[NSArray arrayWithObjects:
secondarySortKey
,nil]];
[request setFetchLimit:30]; //30
NSError *error;
NSArray *results = [[[ChubbyEyetwitterEngine sharedInstance] getManagedObjectContextForUse] executeFetchRequest:request error:&error];
if (error != nil)
{
NSLog(@"Results are %d",[results count]);
}else{
NSLog(@"findAllObjectsInContext error %@",error);
}
}
但这有效
NSArray *tweets = [Tweetary findAllObjectsInContext:[[ChubbyEyetwitterEngine sharedInstance] getManagedObjectContextForUse]];
NSLog(@"Before filter count is %d",[tweets count]);
predicate=[NSPredicate predicateWithFormat:@"smartCollectionIds!=nil && (%@ IN smartCollectionIds)",@"87F173A5-863D-4ECE-9673-A61D8F1E01FC-6285-000009A9CBAF3290"];
predicate=[NSPredicate predicateWithFormat:@"smartCollectionIds!=nil && (%@ IN smartCollectionIds)",@"87F173A5-863D-4ECE-9673-A61D8F1E01FC-6285-000009A9CBAF3290"];
NSArray *bNames = [tweets filteredArrayUsingPredicate:predicate];
NSLog(@"FINAL Results %d",[bNames count]);
+ (NSArray *)findAllObjectsInContext:(NSManagedObjectContext *)context;
{
@synchronized(self){
NSEntityDescription *entity = [self entityDescriptionInContext:context];
NSFetchRequest *request = [[[NSFetchRequest alloc] init] autorelease];
[request setEntity:entity];
NSError *error = nil;
NSArray *results = [context executeFetchRequest:request error:&error];
if (error != nil)
{
//handle errors
//NSLog(@"findAllObjectsInContext error %@",error);
}
return results;
}
}
简而言之,在使用 NSfetchedResultsController 时,我需要我的 fetch 谓词才能工作,而不是先将我的对象加载到数组中,然后再应用我的过滤谓词。谁能指出我正确的方向/弄清楚为什么只有在我将未过滤的数据集加载到数组中之后谓词才有效?