【问题标题】:NSPredicate to compare integer using ContainsNSPredicate 使用 Contains 比较整数
【发布时间】:2012-08-19 03:54:00
【问题描述】:

我正在使用 NSPredicate 使用 UISearchBar 搜索列表中的数字, 它适用于字符串,但不适用于整数

我正在使用以下谓词

predicate = [NSPredicate predicateWithFormat:[NSString stringWithFormat:@"%@ contains[c]  %d", @"number", [searchBar.text intValue]]];
[objectArray filterUsingPredicate:predicate];
[tableview reloadData];

例如,如果我键入 1,则必须列出数组中的所有元素,我已经尝试过 == 如果尝试了任何解决方法,它只适用于确切的数字?

现在,如果我使用此方法“无法将 in/contains 运算符与集合一起使用”,则会出现错误

【问题讨论】:

  • 什么是“数字”?那是字典里的键吗?
  • number 是我的名为 student 的自定义类的属性之一,它有两个属性 int number 和 NSString *name

标签: iphone objective-c nspredicate


【解决方案1】:

我认为这个谓词应该适合你:

predicate = [NSPredicate predicateWithFormat:@"self.number.stringValue CONTAINS %@",searchBar.text];

考虑到这一点,我不确定为什么 self.number.stringValue 有效,但是当我测试它时它确实有效(self.number 是一个 int)。不知道为什么我可以将 stringValue 发送到 int?

【讨论】:

  • 谓词使用键值编码来获取它们的值,键值编码总是将属性提升到对象,即使它们只是原子 C 值。
【解决方案2】:

使用谓词可能会很棘手,所以也许另一种方法对你有用:

NSInteger index = 0;
while (index < objectArray.count)
{
    NSString *currentString = [objectArray objectAtIndex:index];
    if ([currentString rangeOfString:searchBar.text].length == 0)
    {
        [objectArray removeObjectAtIndex:index];
        continue;
    }
    index++;
} 

在这里,数组中不包含 searchBar 文本的所有字符串都将被删除。

【讨论】:

    猜你喜欢
    • 2011-11-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-07-13
    • 2015-05-05
    • 2011-12-29
    • 2018-12-28
    • 2012-06-29
    相关资源
    最近更新 更多