How to use predicates with fetchRequest in Core Data

前端 未结 1 1818
独厮守ぢ
独厮守ぢ 2020-12-16 16:45

I pass a contact Identifier from Contacts tableview controller to another Location tableview controller. So I define a delegate ContactSelectionDelegate and implement metho

1条回答
  •  既然无缘
    2020-12-16 17:14

    First of all get rid of all NSString and NSDictionary occurrences. This is Swift!. Use the Swift native structs String and Dictionary.

    Second of all put always all good code in the do scope of a do - catch block.

    A CoreData predicate has a simple format attribute == value which is very similar to aContact.uniqueId! == contactIdentifierString:

    var contactIdentifierString = ""
    
    func userSelectedContact(contactIdentifier: String) {
    
        let context = (UIApplication.shared.delegate as! AppDelegate).persistentContainer.viewContext
    
        do {
            let fetchRequest : NSFetchRequest = Contact.fetchRequest()
            fetchRequest.predicate = NSPredicate(format: "uniqueId == %@", contactIdentifier)
            let fetchedResults = try context.fetch(fetchRequest) as! [Contact]
            if let aContact = fetchedResults.first {
               providerName.text = aContact.providerName
            }
        }
        catch {
            print ("fetch task failed", error)
        }
    
    }
    

    The code assumes that there is a NSManagedObject subclass Contact containing

    @nonobjc public class func fetchRequest() -> NSFetchRequest {
        return NSFetchRequest(entityName: "Contact")
    }
    

    0 讨论(0)
提交回复
热议问题