I pass a contact Identifier from Contacts tableview controller to another Location tableview controller. So I define a delegate ContactSelectionDelegate and implement metho
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")
}