【问题标题】:NSPredicate - Contains Not Functioning As ExpectedNSPredicate - 包含未按预期运行
【发布时间】:2014-11-30 22:12:35
【问题描述】:

我在 NSMutableArray 上使用 NSPredicate,如下所示,从 XML Sheet 填充

//Get XML Data
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"breosla_db" ofType:@"xml"];
NSDictionary *xmlDoc = [NSDictionary dictionaryWithXMLFile:filePath];
//Place in Mutable Array
NSMutableArray *data = [xmlDoc valueForKeyPath:@"row"];
NSLog(@"Data %@", data[0]);

NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"ID contains[c] '2'"];
NSArray *filtered = [data filteredArrayUsingPredicate:bPredicate];

日志中的数据是这样的:

Data {
ID =     (
    2
);
address1 =     (
    "123 Fake Street"
);
address2 =     (
    "A Sleepy Town"
);
address3 =     (
);
county =     (
);
licenseNo =     (
    12345
);
licenseType =     (
    "Trader"
);
licenseeName =     (
    "Mr. Trader"
);
nominessName =     (
);
tradingName =     (
    "Trading Shop"
);

}

当前谓词:

NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"ID contains[c] '2'"];

仅返回 ID == 2 的数据,例如不返回 12、22、42 等。

其次,我不能按例如过滤。所有包含“e”的名称:

NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"tradingName contains[c] 'e'"];

每个位置的“数据”NSMutableArray 包含与日志中显示的数据相似的数据。

【问题讨论】:

    标签: ios nsmutablearray nsarray nsdictionary nspredicate


    【解决方案1】:

    看起来您的数据包含一个字典数组,并且每个字典键的值也是(单个元素)数组。您可以看到这一点,因为您的日志显示

    ID =     (
        2
    );
    etc
    

    ( ) 表示数组。因此,要使谓词起作用,您需要使用“ANY”,如下所示:

    NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"ANY ID contains[c] '2'"];
    

    NSPredicate *bPredicate = [NSPredicate predicateWithFormat:@"ANY tradingName contains[c] 'e'"];
    

    但您最好对数据进行重构,以使这些值不会嵌入到数组中。

    【讨论】:

    • 这是正确的,是的,我的数据需要重新建模!谢谢。
    【解决方案2】:

    您的谓词似乎仅适用于 ID 或 tradingName。假设 data[0] 包含完整的 xml 元素,而不是使用以下;

    NSPredicate *idPredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] '2'"];
    [data filterUsingPredicate:idPredicate];

    对于包含“e”的tradingName:

    NSPredicate *namePredicate = [NSPredicate predicateWithFormat:@"SELF contains[c] 'e'"];
    [data filterUsingPredicate:namePredicate];

    查看此reference 以获得更多帮助。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-11-12
      • 1970-01-01
      • 2020-06-28
      • 2012-02-18
      • 2018-01-18
      • 2012-06-14
      相关资源
      最近更新 更多