我想在通知中发送枚举作为对象:
enum RuleError:String {
case Create,Update,Delete
}
class myClass {
func foo() {
NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification",object: RuleError.Create)
}
}
不幸的是,这不起作用,因为枚举与AnyObject不匹配?
知道如何规避这个问题吗?
解决方法
您正在使用的函数中的对象参数是发件人,发布通知的对象,而不是参数.查看文档
here.
您应该将要发送的枚举值作为参数放在用户信息字典中,并使用以下方法:
func postNotificationName(_ aName: String,object anObject: AnyObject?,userInfo aUserInfo: [NSObject : AnyObject]?)
在你的情况下:
let userInfo = ["RuleError" : RuleError.Create.rawValue]
NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification",object: self,userInfo:userInfo)
要处理通知,请先注册:
NSNotificationCenter.defaultCenter().addobserver(
self,selector: "handleRuleFailNotification:",name: "RuleFailNotification",object: nil)
然后处理它:
func handleRuleFailNotification(notification: NSNotification) {
let userInfo = notification.userInfo
RuleError(rawValue: userInfo!["RuleError"] as! String)
}