Ios 从NSNotification获取的字符串中删除可选项

Ios 从NSNotification获取的字符串中删除可选项,ios,string,swift4,optional,Ios,String,Swift4,Optional,我从NSNotification中获得一个字符串,但面临附加到给定字符串的可选关键字问题,希望从字符串中删除可选关键字,以下是我的代码: func getAlertMsg(notification:NSNotification!){ if let strAlert = notification?.object.debugDescription{ print(strAlert) Helper .showAsAlert(strMessa

我从NSNotification中获得一个字符串,但面临附加到给定字符串的可选关键字问题,希望从字符串中删除可选关键字,以下是我的代码:

func getAlertMsg(notification:NSNotification!){
        if let strAlert = notification?.object.debugDescription{
            print(strAlert)
            Helper .showAsAlert(strMessage: strAlert, VC: self)
        }
    }
回应

{
"status": true,
"message": "User created",
"user_detail":{}
}

对于您当前的代码。应该是:

func getAlertMsg(notification: NSNotification) {
    if let string = notification.object as? String {
        Helper.showAsAlert(strMessage: string, VC: self)
    }
}
let strMessage = responseVal.value(forKey: "message") as? String
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "RegAlertMsg"), 
                                object: strMessage) 
此外,您的通知帖子应为:

func getAlertMsg(notification: NSNotification) {
    if let string = notification.object as? String {
        Helper.showAsAlert(strMessage: string, VC: self)
    }
}
let strMessage = responseVal.value(forKey: "message") as? String
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "RegAlertMsg"), 
                                object: strMessage) 

只需传递
strMessage
。不要敲打(!)它,否则当
responseVal.value(forKey:“message”)为时,您的应用程序将崩溃?字符串
失败。

我从通知中访问了对象,如下所示:

@objc func updateActivityDetailWithUserEvent(通知:NSNotification){ //做事

    print("notification obj is ",notification)

    let activityData:[String: ActivityFeed] = notification.object  as! [String: ActivityFeed]
    activityObj = activityData ["activityUpdated"]!
    DispatchQueue.main.async {

    //Update UI From Main Thread
        self.setUpdatedCell()


    }

}
//发布通知并将字典作为参数传递的方式:

从要使用Dictionary参数发布通知的方法调用它:

让activityData:[字符串:ActivityFeed]=[“ActivityUpdate”:activityFeedObj]

    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "activityUpdated"), object: activityData)

这里我从生成NSNotification时传递的通知中获取Dictionary对象,您可以按照类似的方法获取字符串值

发送非可选字符串不是更容易吗?为什么参数IUO?使用非可选变量,或者学习如何“展开可选”(这是要搜索的关键字)在Swift中(这是非常基础和非常有用的知识)。@mag_zbc
debugDescription
中的字符串已经可以包含literal
“可选”(“
显示您首先创建字符串的代码。@priyanshu需要更多的代码。什么是
responseVal
,它是如何创建的?不要在评论中发布代码,编辑原始问题他已经使用可选链接来打开字符串-
如果让strAlert=…
@mag_zbc但是可选链接是在错误的地方做的。@mag_zbc无论如何,我已经更新了我的答案。但是
NSNotification
中的
object
是最后一个可选选项。他只是使用
NSNotification!
然后使用
notification?.object.debugDescription
@priyanshu这个答案对你有用吗,因为如果不合适,我可能会删除它一点也不help@staticVoidMan:您好,这确实有帮助,我使用的debugDescription是可选的,所以我只使用了通知?.object。顺便说一句,非常感谢!!!太糟糕了,我只能使用一次下一票强制展开我添加了示例,只是为了让您了解我如何从通知访问对象,您可以更改这是根据你的要求。