core-data - NSPredicate 用于搜索小数

标签 core-data swift nspredicate

我正在尝试构建搜索功能,用户可以搜索“10”并返回包含带有“10”的交易金额的结果,显然......

获取以下数据集:

10.35 70.51 64.02

使用以下谓词语句:

transaction.amount CONTAINS[cd] 10

以上所有交易都会被返回,因为它们都包含“1”、“0”或两者的组合,我只想要顺序包含“10”的结果。

我尝试了多种不同的方法,包括将值字段设为字符串、十进制和 double 。

有谁知道我如何使用 NSPredicate 来做到这一点?我宁愿不走拉下所有记录然后使用正则表达式或类似的东西的路线。

干杯

最佳答案

使用 NSString

如果您将金额存储为字符串(我觉得这有点奇怪),则以下内容将按您的意愿工作:

NSArray *decimals = @[@"10.35", @"70.51", @"64.02", @"11.10"];
NSLog(@"Decimals: %@", decimals);
NSArray *tens = [decimals filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF CONTAINS[cd] '10'"]];
NSLog(@"Tens: %@", tens);

给出以下输出:

Decimals: (
    "10.35",
    "70.51",
    "64.02",
    "11.10"
)
Tens: (
    "10.35",
    "11.10"
)

使用 NSNumber

但是,如果您想将金额保留为数字,您可以执行类似的操作,滥用 NSNumberdescription:

NSArray *decimals = @[@(10.35), @(70.51), @(64.02), @(11.10)];
NSLog(@"Decimals: %@", decimals);
NSArray *tens = [decimals filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"SELF.description CONTAINS[cd] '10'"]];
NSLog(@"Tens: %@", tens);

给出以下输出:

Decimals: (
    "10.35",
    "70.51000000000001",
    "64.02",
    "11.1"
)
Tens: (
    "10.35",
    "70.51000000000001"
)

正如您从输出中看到的,它没有给您想要的结果,因此可以在您的事务 NSManagedObject 上实现 getter,如下所示:

- (NSString *)amountSearch {
    return [NSString stringWithFormat:@"%.2f", self.amount.doubleValue];
}

你的谓词将是这样的:

transaction.amountSearch CONTAINS[cd] '10'

关于core-data - NSPredicate 用于搜索小数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27481021/

相关文章:

swift - pod 安装后找不到 '.xcworkspace'

ios - 检查以确保核心数据中的实体属性在保存时不相同

ios - NSPredicate 中的不一致

ios - 找不到实体名称的 NSManagedObjectModel

ios - 将 'didMoveCellFromIndexPathToIndexPathBlock' 与核心数据一起使用

swift - 如何在 PDF 文件上保存水印并导出到桌面 macOS Mojave

swift - 调用 AVAudioRecorder 的初始化程序 - Swift 2.0

cocoa - 核心数据 : Find minimum of calculated property

ios - 设计一个核心数据模型来记住以前的对象状态

ios - 在同一个 UITableView 的不同部分显示多个 NSFetchedResultsControllers