首先摆脱所有NSString
和NSDictionary
事件.这是斯威夫特!使用Swift本机结构String
和Dictionary
.
其次,总是把所有好的代码放在do
一个do - catch
块的范围内.
CoreData谓词具有attribute == value
与以下内容非常类似的简单格式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) } }
代码假定有一个NSManagedObject
子类Contact
包含
@nonobjc public class func fetchRequest() -> NSFetchRequest{ return NSFetchRequest (entityName: "Contact") }