avatar

SwiftUI-CoreData中使用NSPredicate过滤

在利用CoreData来存储数据的时候,如果需要过滤出我们需要的结果怎么办呢?

NSPredicate

1
@interface NSPredicate : NSObject

where to use

1
@FetchRequest(entity: , sortDescriptors: , predicate: , animation: )

Usage

init

1
2
NSPredicate(format: "universe == 'Star'"))
NSPredicate(format: "universe == %@", "Star"))

%@是占位符

Comparison

1
2
grade == "7"
firstName like "Shaffiq"

==like关键字都可以,此外还有<>

Involve

1
2
"universe IN %@", ["Aliens", "Firefly", "Star Trek"]
"name contains[c] %@", "Star"

(In the example, like[cd] is a modified “like” operator that is case-insensitive and diacritic-insensitive.)

more to see Predicate Format String Syntax

Regex

1
"name matches %@", "[0-9]o{2}"

Logic

1
2
"name BEGINSWITH %@", "E"
"name ENDSWITH %@", "E"

还可以使用NOT AND OR等基础关键字

Advanced

To see Predicate Programming Guide

文章作者: X Mεl0n
文章链接: http://www.zrzz.site/2020/06/27/SwiftUI-CoreData%E4%B8%AD%E4%BD%BF%E7%94%A8NSPredicate%E8%BF%87%E6%BB%A4/
版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 4.0 许可协议。转载请注明来自 X Mεl0n | 随手记

评论