我有这行代码在第一次成功运行时成功运行:
notificationCenter.postNotificationName(NotificationContactCreated, object: nil)
但是稍后当调用相同函数中的同一行时,我得到fatal error
:
致命错误:在解包可选值时意外发现nil
然而,如果我设置了代码,则通知中心和NotificationContactCreated都已设置。
我绕圈子找不到原因......
任何帮助......请????
由于
这是通知中心:
//
// notification center to be used across phone app
//
lazy var notificationCenter: NSNotificationCenter = {
return NSNotificationCenter.defaultCenter()
}()
这里是调用它的函数:
func updateAccount(firstName: String, lastName: String, emailAddress: String, companyName: String, isSelf: Bool) -> Void {
// we are going to update the Contacts entity
let fetchRequest = NSFetchRequest(entityName: entityNameContacts)
// filter on first name + last name + email address
fetchRequest.predicate = NSPredicate(format: "firstName == %@ && lastName == %@ && emailAddress == %@", firstName, lastName, emailAddress)
do {
// try to get an array of accounts based on filter, should only be one returned
let contactsArray = try context.executeFetchRequest(fetchRequest) as? [Contacts]
// if there is a record we just want to update it
if contactsArray?.count > 0 {
// grab the reading object
let contact = contactsArray![0]
// and update its data
contact.firstName = firstName
contact.lastName = lastName
contact.emailAddress = emailAddress
contact.companyName = companyName
}
else {
// otherwise we need to insert a new record
let newContact: Contacts = NSEntityDescription.insertNewObjectForEntityForName(entityNameContacts, inManagedObjectContext: context) as! Contacts
// and populate with new data
newContact.firstName = firstName
newContact.lastName = lastName
newContact.emailAddress = emailAddress
newContact.companyName = companyName
newContact.isSelf = isSelf
}
// write amends
saveContext()
self.notificationCenter.postNotificationName(NotificationContactCreated, object: nil)
} catch {
print("func updateAccount(firstName: String, lastName: String, emailAddress: String, companyName: String, isSelf: Bool) -> Void !!!ERROR")
}