NSPredicate数组内对象内的过滤器数组

时间:2014-01-13 15:33:59

标签: ios objective-c

我有以下方法:

- (NSMutableArray *)getFilteredArrayFromArray:(NSMutableArray *)array withText:(NSString *)text {

if ([array count] <= 0)
    return nil;

NSMutableArray *arrayToFilter = [NSMutableArray arrayWithArray:array];
NSString *nameformatString = [NSString stringWithFormat:@"stationName contains[c] '%@'", text];
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:nameformatString];

NSString *descformatString = [NSString stringWithFormat:@"stationTagline contains[c] '%@'", text];
NSPredicate *descPredicate = [NSPredicate predicateWithFormat:descformatString];

NSString *aToZformatString = [NSString stringWithFormat:@"stationSearchData.browseAtozArray.city contains[c] '%@'", text];
NSPredicate *aToZPredicate = [NSPredicate predicateWithFormat:aToZformatString];

NSPredicate * combinePredicate = [NSCompoundPredicate orPredicateWithSubpredicates:[NSArray arrayWithObjects:namePredicate, descPredicate, aToZPredicate, nil]];

[arrayToFilter filterUsingPredicate:combinePredicate];

return arrayToFilter;
}

前2个谓词工作正常。但最后一个(aToZPredicate),是行不通的。 stationSearchData是一个StationSearchData对象,而browseAtozArray是一个NSMutableArray。

如何使用谓词基本上搜索数组中数组内的数组?

以下是StationSearchData对象的接口:

@interface StationSearchData : NSObject

@property (nonatomic, strong) NSString *location;
@property (nonatomic, strong) NSString *city;
@property (nonatomic, strong) NSString *latitude;
@property (nonatomic, strong) NSString *longitude;

@property (nonatomic, strong) NSMutableArray *browseAtozArray;
@property (nonatomic, strong) NSMutableArray *genreArray;

@end

谢谢!

1 个答案:

答案 0 :(得分:29)

首先,您不应该使用stringWithFormat来构建谓词。这可能会导致 搜索文本包含'"等特殊字符时出现问题。 所以你应该替换

NSString *nameformatString = [NSString stringWithFormat:@"stationName contains[c] '%@'", text];
NSPredicate *namePredicate = [NSPredicate predicateWithFormat:nameformatString];

通过

NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"stationName contains[c] %@", text];

要在数组中搜索,您必须在谓词中使用“ANY”:

NSPredicate *aToZPredicate =
  [NSPredicate predicateWithFormat:@"ANY stationSearchData.browseAtozArray.city CONTAINS[c] %@", text];