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

前端之家收集整理的这篇文章主要介绍了ios – 数组内的对象内的NSPredicate过滤器数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有以下方法
- (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

谢谢!

解决方法

首先,你不应该使用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];

猜你在找的iOS相关文章