使用NSPredicate在NSArray中搜索自定义对象中的字符串

时间:2016-08-01 10:49:43

标签: ios swift nsarray nspredicate

我有两个类,如下所示:

class City : NSObject{
    var header:String? = nil
    var areas:NSMutableArray? = nil  //Contain array of Area

    //Return array of City objects
    class func generate(cityCount:NSInteger) -> NSMutableArray{...} 
}

class Area : NSObject{
    var title:String? = nil
    var address:String? = nil
}
    //Return array of Area objects
    class func generate(areaCount:NSInteger) -> NSMutableArray {...} 

现在,我在我的viewcontroller中声明了像这样的城市数组:

var cities = City.generate(200)

当我使用NSPredicate搜索内部标题时,它可以正常工作

let pred = NSPredicate(format: "SELF.header CONTAINS %@",searchString)
let filteredCities = self.cities.filteredArrayUsingPredicate(pred)

但是当我搜索cities->areas->address时(我想搜索地址)。它不起作用。它始终返回0对象。在这里我正在尝试:

let pred = NSPredicate(format: "SELF.areas.address CONTAINS %@",searchString) //name
let filteredCities = (self.cities as NSArray).filteredArrayUsingPredicate(pred)

修改

我只需要包含匹配地址的区域对象。 我试过了:

let pred = NSPredicate(format: "ANY areas.address CONTAINS %@",searchString)

这为City对象提供了所有区域对象。

enter image description here

提前致谢。

2 个答案:

答案 0 :(得分:1)

尝试这样

import java.io.FileInputStream;
import com.fasterxml.jackson.core.JsonFactory;
import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonToken;

public class TestClass {

    public static void main(String[] args) {
        try (FileInputStream fis = new FileInputStream("yourpath/transactions.json")) {
            JsonFactory jf = new JsonFactory();
            JsonParser jp = jf.createParser(fis);
            //System.out.println(JsonToken.START_ARRAY);
            // jp.setCodec(new ObjectMapper());
            jp.nextToken();
            while (jp.hasCurrentToken()) {

                if (jp.getCurrentToken().equals(JsonToken.START_OBJECT)
                        || jp.getCurrentToken().equals(JsonToken.START_ARRAY)
                        || jp.getCurrentToken().equals(JsonToken.END_ARRAY)
                        || jp.getCurrentToken().equals(JsonToken.END_OBJECT)) {
                } else {
                    System.out.print(jp.getText());
                    jp.nextToken();
                    System.out.print(":");
                    System.out.print(jp.getText());
                    System.out.println();
                }
                jp.nextToken();
            }
        } catch (Exception ex) {
            ex.printStackTrace();
        }
    }
}

答案 1 :(得分:0)

试试这个兄弟,

让pred = NSPredicate(格式:“SELF包含[c]%@”,searchString)  let filteredCities = self.area.filteredArrayUsingPredicate(pred)