NSPredicate 与字符串完全匹配
NSPredicate Exact Match with String
你好,我正在研究 swift。我需要知道如何找到与确切字符串匹配的结果。这是我的代码
let userID: String = String(sender.tag)
// Create a Predicate with mapping to trip_id
let filterByRequest: NSPredicate = NSPredicate(format: "%K.%K CONTAINS[c] %@", "ProductRequest", "user_id", userID)
// Filter your main array with predicate, resulting array will have filtered objects
let filteredArray: [AnyObject] = self.array.filteredArrayUsingPredicate(filterByRequest)
问题是如果用户 ID 是 69,它会显示 ID 为 69、6 和 9 的用户的结果。
我用谷歌搜索,但我找到了一些与我的问题相关的答案,但它们都在 objective C 中。
在谓词中使用 MATCHES 如下:
let filterByRequest: NSPredicate = NSPredicate(format: "%K.%K MATCHES %@", "ProductRequest", "user_id", userID)
希望对您有所帮助..
要测试是否完全相等,只需使用 ==
而不是 CONTAINS
:
NSPredicate(format: "%K.%K == %@", ...)
这也可以与 [c]
结合使用以实现不区分大小写的相等性:
NSPredicate(format: "%K.%K ==[c] %@", ...)
你好,我正在研究 swift。我需要知道如何找到与确切字符串匹配的结果。这是我的代码
let userID: String = String(sender.tag)
// Create a Predicate with mapping to trip_id
let filterByRequest: NSPredicate = NSPredicate(format: "%K.%K CONTAINS[c] %@", "ProductRequest", "user_id", userID)
// Filter your main array with predicate, resulting array will have filtered objects
let filteredArray: [AnyObject] = self.array.filteredArrayUsingPredicate(filterByRequest)
问题是如果用户 ID 是 69,它会显示 ID 为 69、6 和 9 的用户的结果。
我用谷歌搜索,但我找到了一些与我的问题相关的答案,但它们都在 objective C 中。
在谓词中使用 MATCHES 如下:
let filterByRequest: NSPredicate = NSPredicate(format: "%K.%K MATCHES %@", "ProductRequest", "user_id", userID)
希望对您有所帮助..
要测试是否完全相等,只需使用 ==
而不是 CONTAINS
:
NSPredicate(format: "%K.%K == %@", ...)
这也可以与 [c]
结合使用以实现不区分大小写的相等性:
NSPredicate(format: "%K.%K ==[c] %@", ...)