NSPredicate数组内对象内的过滤器数组 [英] NSPredicate filter array within object within array

查看:114
本文介绍了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。

The first 2 predicates work fine. But the last one (aToZPredicate), is not working. stationSearchData is a StationSearchData object, and browseAtozArray is an NSMutableArray.

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

How can I use a predicate to essentially search an array within an array within an array?

这是StationSearchData对象的接口:

Here is the interface for the StationSearchData object:

@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 来构建谓词。如果搜索文本包含任何特殊字符,例如',则会导致
问题。
所以你应该替换

First of all, you should not use stringWithFormat to build predicates. This can cause problems if the search text contains any special characters like ' or ". So you should replace

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

by

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

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

To search within an array, you have to use "ANY" in the predicate:

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

这篇关于NSPredicate数组内对象内的过滤器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆