我想在通知中将枚举作为对象发送:
enum RuleError:String {
case Create, Update, Delete
}
class myClass {
func foo() {
NSNotificationCenter.defaultCenter().postNotificationName("RuleFailNotification",
object: RuleError.Create)
}
}
不幸的是,这不起作用,因为枚举不匹配 AnyObject?
。
知道如何避免这个问题吗?
最佳答案
您正在使用的函数中的 object
参数是发送者,即发布通知的对象,而不是参数。查看文档 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)
}
关于ios - 如何在 Swift 的通知中发送枚举值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33800293/