How to use predicates with fetchRequest in Core Data

一世执手 提交于 2019-11-29 07:03:21

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> = 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<Contact> {
    return NSFetchRequest<Contact>(entityName: "Contact")
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!