Несколько NSPredicates для NSFetchRequest в Swift?

В настоящее время у меня есть простой NSFetchRequest с ассоциированным NSPredicate. Однако я надеюсь, что вы можете добавить несколько предикатов. Я видел примеры в Objective C, но не для Swift.

Можете ли вы определить список NSPredicate или добавить несколько объектов NSPredicate к одному NSFetchRequest каким-то образом?

Спасибо!

Ответы

Ответ 1

Вы можете использовать "NSCompoundPredicate". Например:

    let converstationKeyPredicate = NSPredicate(format: "conversationKey = %@", conversationKey)
    let messageKeyPredicate = NSPredicate(format: "messageKey = %@", messageKey)
    let andPredicate = NSCompoundPredicate(type: NSCompoundPredicateType.AndPredicateType, subpredicates: [converstationKeyPredicate, messageKeyPredicate])
    request.predicate = andPredicate

Вы можете изменить на "AndPredicateType" или "OrPredicateType"

Ответ 2

Обновление для Swift 4

        let predicateIsNumber = NSPredicate(format: "isStringOrNumber == %@", NSNumber(value: false))
        let predicateIsEnabled = NSPredicate(format: "isEnabled == %@", NSNumber(value: true))
        let andPredicate = NSCompoundPredicate(type: NSCompoundPredicate.LogicalType.and, subpredicates: [predicateIsNumber, predicateIsEnabled])

        //check here for the sender of the message
        let fetchRequestSender = NSFetchRequest<NSFetchRequestResult>(entityName: "Keyword")
        fetchRequestSender.predicate = andPredicate

Изменение последней версии Swift:

NSCompoundPredicateType.AndPredicateType replaced by `NSCompoundPredicate.LogicalType.and `

Надеюсь, это поможет!!!

Спасибо