2016-02-08 12 views
18

Hiện tại, tôi có một NSFetchRequest đơn giản với một NSPredicate được liên kết. Tuy nhiên, Im hy vọng có một cách bạn có thể nối thêm nhiều vị từ. Tôi đã nhìn thấy các ví dụ trong Objective C, nhưng không có gì cho Swift.Nhiều NSPredicates cho NSFetchRequest trong Swift?

Bạn có thể xác định danh sách NSPredicate hoặc nối nhiều đối tượng NSPredicate vào một NSFetchRequest đơn lẻ không?

Cảm ơn!

+2

API là như nhau nên các ví dụ bạn đã nhìn thấy là hợp lệ - hãy thử nó và mã hiển thị nếu bạn gặp rắc rối – Wain

Trả lời

31

Bạn có thể sử dụng "NSCompoundPredicate". Ví dụ:

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

Bạn có thể thay đổi thành "AndPredicateType" hoặc "OrPredicateType"

+0

Nhưng nếu messageKeyPredicate trong ví dụ này, chỉ tồn tại trong các tình huống nhất định. Có một cách thanh lịch để tránh mã spagetti trong cố gắng để xây dựng các NSCompoundPredicate? – ardevd

+0

Nevermind, chỉ cần xây dựng một danh sách các NSPredicates là tốt! Cảm ơn bạn! – ardevd

+0

Chúng tôi có thể sử dụng andPredicate - hoặc sự khác biệt là gì? let andPredicate = NSCompoundPredicate (vàPredicateWithSubpredicates: [predicateIsNumber, predicateIsEnabled]) – davidrynn

5

Cập nhật cho 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 

Sự thay đổi mới nhất Swift Phiên bản:

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

Hy vọng nó sẽ giúp !!!

Cảm ơn

Các vấn đề liên quan