gpt4 book ai didi

ios - NSPredicate 按名称传递 "multiple"参数 [在 Swift 中]

转载 作者:可可西里 更新时间:2023-11-01 00:05:28 25 4
gpt4 key购买 nike

是否可以通过命名而不是 %@

将多个参数传递给 NSPredicate

例如,我有一个直接传递参数meyou

public static func ConversationByUserId( userId : String ) -> [Message] {

// Either Created By me and sent to you.
// Or, created by you and sent to me


let me = UserRepo.GetLoggedInUser()?.id

var format = "( createdBy == '" + me! + "' && createdTo == '" + userId + "') "
format += " || ( createdBy == '" + userId + "' && createdTo == '" + me! + "') "


print(format)
//prints: ( createdBy == '1' && createdTo == '5') || ( createdBy == '5' && createdTo == '1')


let predicate = NSPredicate(format: format)

return Filter(predicate);


}

注意:Filter(predicate) 执行操作并返回结果。到目前为止,一切都很好。我得到了预期的结果。但我猜这可能会产生像 SQL 攻击这样的问题。

我可以做如下的事情吗:如果可以,怎么做?

  var format = "( createdBy == @me  && createdTo == @you ) "
format += " || ( createdBy == @you && createdTo == @me ) "


let predicate = NSPredicate(format: format, [ "me" : me, "you" : you ])

到目前为止我取得的成绩是:

    format = "( createdBy == %@  && createdTo == %@ ) "
format += " || ( createdBy == %@ && createdTo == %@ ) "


let predicate = NSPredicate(format: format, me!, you, me!, you)

最佳答案

您可以使用 NSPredicate 的 predicateWithSubstitutionVariables(参见 Apple Docs)。像往常一样创建谓词,使用“$variable”代替您要替换的值:

var format = "( createdBy == $me  && createdTo == $you ) "
format += " || ( createdBy == $you && createdTo == $me ) "
let predicate = NSPredicate(format: format)

然后用变量名和你想传递的值创建一个字典:

let subVars = ["me" : me!, "you" : you!]

最后用您的值替换变量名创建谓词:

let finalPredicate = predicate.predicateWithSubstitutionVariables(subVars)

关于ios - NSPredicate 按名称传递 "multiple"参数 [在 Swift 中],我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38136341/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com