Reputation: 3805
This is occuring in Swift 1.1, in the following code "theNotification" is occasionally returned as nil, which is crashing NSNotificationCenter.postNotification(). I can't figure out why, as it's very infrequent, might be because the code is in an iOS8 keyboard extension, but I don't know of any reasons why that would matter.
class func sendNotificationValue(name : String, value: Int) {
let notificationQ = NSNotificationCenter.defaultCenter()
let userDict = ["value": value]
let theNotification = NSNotification(name: name, object: nil, userInfo: userDict)
notificationQ.postNotification(theNotification)
}
But my other problem is because theNotification isn't an optional, I can't check it for nil, I get "NSObject does not conform to protocol 'NilLiteralConvertible", so I can't defensively program to prevent the crash.
Obviously the best solution is to figure out why it's returning nil in the first place, but I'm trying to at least not crash in this scenario. Any suggestions for why it would return nil, or how I can check theNotification for nil here?
Resolution:
The worst bugs make you feel silly when you solve them and I feel extra silly about this one. The problem was never with nil NSNotification allocations, LLDB was lying to me about that as it is wont to do in Swift occasionally. Looking at the notification with PO revealed it was being allocated fine.
My real problem turns out to be that extensions and their controllers can be unloaded from memory occasionally. I was not removing my notification handlers when it was, so when it reloaded NSNotificationCenter attempted to deliver notifications to the unloaded observers, so crash. Something to remember about using NSNotifications in controllers/objects that can be unloaded, remove those observers when they are.
Upvotes: 2
Views: 677
Reputation: 536018
Simply type theNotification
as an Optional when you create it:
let theNotification: NSNotification? =
NSNotification(name: name, object: nil, userInfo: userDict)
Now it is legal to compare theNotification
with nil
.
Upvotes: 2