NSPredicate与数组无法正常工作

时间:2013-12-17 14:56:11

标签: ios objective-c uitextfield nspredicate

我试图弄清楚为什么这段代码没有显示相同的结果,以及为什么两个字符串不相等。我在UITextfield中插入的值是“a”,如日志中所示。

- (void)resultsForSearchString:(NSString *)searchString
{   
    NSString *str = [NSString stringWithFormat:@"a"];

    NSLog(@"searchString = %@", searchString);
    NSLog(@"str = %@", str);

    NSMutableArray *array = [NSMutableArray arrayWithObjects:@"Nick", @"Ben", @"Adam", @"Melissa", nil];

    NSPredicate *aPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", searchString];
    NSArray *beginWithA = [array filteredArrayUsingPredicate:aPredicate];
    NSLog(@"%@", beginWithA);

    aPredicate = [NSPredicate predicateWithFormat:@"SELF beginswith[c] %@", str];
    beginWithA = [array filteredArrayUsingPredicate:aPredicate];
    NSLog(@"%@", beginWithA);

    if ([str isEqualToString:searchString]) {
        NSLog(@"true");
    }
    else {
        NSLog(@"false");
    }
}

此方法被称为UIControlEventEditingChanged的触发器:

- (void)textFieldDidChange:(UITextField *)sender
{
    [self resultsForSearchString:sender.text];
}

这是输出:

2013-12-17 16:44:49.845 SevenOut[7381:70b] searchString = ​a 
2013-12-17 16:44:49.846 SevenOut[7381:70b] str = a
2013-12-17 16:44:52.676 SevenOut[7381:70b] (
)
2013-12-17 16:44:53.956 SevenOut[7381:70b] (
    Adam
)
2013-12-17 16:44:54.988 SevenOut[7381:70b] false

1 个答案:

答案 0 :(得分:0)

我刚测试了你的代码,它运行正常。

2013-12-17 15:02:45.778 MessAbout[3856:70b] searchString = a | length = 1
2013-12-17 15:02:45.779 MessAbout[3856:70b] str = a | length = 1
2013-12-17 15:02:45.779 MessAbout[3856:70b] (
    Adam
)
2013-12-17 15:02:45.779 MessAbout[3856:70b] (
    Adam
)
2013-12-17 15:02:45.780 MessAbout[3856:70b] true

如果您将前2个日志更改为

NSLog(@"searchString = %@ | length = %u", searchString, [searchString length]);
NSLog(@"str = %@ | length = %u", str, [str length]);

然后你可能会发现为什么它们不是同一个字符串。