ios - 如何在 Swift 的通知中发送枚举值?

标签 ios swift enums nsnotificationcenter

我想在通知中将枚举作为对象发送:

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/

相关文章:

ios - 使用 Simperium 同步无符号数

ios - 核心数据对象注入(inject)(带有依赖项) Storyboard

ios - 隐藏 sfsafariviewcontroller 中的控件

通用枚举到int的C#非装箱转换?

实现接口(interface)的枚举的 Java 参数和返回类型

javascript - 将 Iframe 嵌入图像内

ios - 为什么使用开发者身份或第三方通过后端进行身份验证

ios - 如何创建自定义图层类

ios - 我想知道如何让一个单元格快速转到 Xcode 9 中的另一个 View Controller

swift - 禁止 swift 中间接枚举的一些特定情况