2012-11-08 182 views
2

我的谓词不断使我的应用程序崩溃,消息Unsupported function expression FUNCTION(SELF, "filterDistanceWithLatitude:" , latitude, longitude)。有谁知道如何解决这一问题?NSPredicate With FUNCTION Not Working

- (void)setUpFetchedResultsController 
{ 
    NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:@"NextTime"]; //Retrieve data for the place entity 
    request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES selector:@selector(localizedCaseInsensitiveCompare:)]]; //How to sort it 
    self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.context sectionNameKeyPath:nil cacheName:nil]; //Puts the data in a NSFetchedResultsController which is oddly located in CoreDataTableViewController //Puts the data in a NSFetchedResultsController which is oddly located in CoreDataTableViewController 
    self.filtered = self.fetchedResultsController.fetchedObjects; 
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"FUNCTION(self, 'filterByDistanceWithLatitude:', latitude, longtitude) > 20"]; 
    self.filtered = [self.filtered filteredArrayUsingPredicate:predicate]; 
} 

- (double)filterByDistanceWithLatitude:(NSNumber *)latitude andLongitude:(NSNumber *)longitude 
{ 
    CLLocationDegrees latitudeCoor = [latitude doubleValue]; //Puts the latitude into a NextTime object. 
    CLLocationDegrees longitudeCoor = [longitude doubleValue]; //Puts the longtitude into a NextTime object. 

    CLLocation *loc1 = [[CLLocation alloc] initWithLatitude:latitudeCoor longitude:longitudeCoor]; 
    CLLocation *loc2 = [[CLLocation alloc] initWithLatitude:self.currentLocation.latitude longitude:self.currentLocation.longitude]; 

    NSNumber *distance = [[NSNumber alloc] initWithDouble:[loc1 distanceFromLocation:loc2]]; 

    return [distance doubleValue]; 
} 

回答

2

甲取为(基于SQL)请求核心数据存储不能使用Objective-C的基于谓词或排序描述符。您只能过滤存储在数据库中的属性。

这里是从“核心数据编程指南”的相关文件:

使用基于瞬态特性 (虽然你可以使用一个谓语不能取瞬态属性在你自己的内存中过滤内存 )。 ...总而言之,如果直接执行提取,您应该通常不会将基于Objective-C的谓词或排序描述符添加到提取请求的 。相反,您应该将这些应用于获取结果 。

有获取和存储的类型之间的一些互动。 ...另一方面,SQL存储编译谓词并将 描述符分类到SQL,并在数据库本身中评估结果。 这主要是为了性能,但这意味着评估 发生在非Cocoa环境中,因此依赖Cocoa的排序描述符(或 谓词)无法工作。

+0

那么是否有另一种方法使用NSPredicate – gsapienza

+0

来解决这个问题@gsapienza:不结合提取的结果控制器。但是您可以获取所有对象(使用'NSArray * allObjects = [context executeFetchRequest:...]',而没有限制谓词),然后将过滤器应用于结果数组(例如'NSArray * filteredObjects = [allObjects filteredArrayUsingPredicate:predicate ]'。 –

+0

更新了代码,仍然有相同的错误。我的谓词格式是否正确? – gsapienza

0

'filterDistanceWithLatitude:' 可能应该是 'filterByDistanceWithLatitude:'

+0

好抓!但我仍然得到相同的错误 – gsapienza