I want to send an enum as an object in a notification :
enum RuleError:String {
case Create, Update, Delete
}
class myClass {
func foo() {
NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification",
object: RuleError.Create)
}
}
Unfortunately this doesn't work since an enum does not match AnyObject?
.
Any idea how to circumvent this problem ?
The object
parameter in the function you're using is the sender, the object posting the notification, not the parameter. Check out the docs here.
You should put the enum value you want to send as a parameter in the user info dictionary and use the following method:
func postNotificationName(_ aName: String,
object anObject: AnyObject?,
userInfo aUserInfo: [NSObject : AnyObject]?)
In your case:
let userInfo = ["RuleError" : RuleError.Create.rawValue]
NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification",
object: self,
userInfo:userInfo)
And to handle the notification, first register for it:
NSNotificationCenter.defaultCenter().addObserver(
self,
selector: "handleRuleFailNotification:",
name: "RuleFailNotification",
object: nil)
Then handle it:
func handleRuleFailNotification(notification: NSNotification) {
let userInfo = notification.userInfo
RuleError(rawValue: userInfo!["RuleError"] as! String)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With