如何使用通知将字符串数据从swift传递到Objective c类

时间:2017-10-12 05:02:17

标签: ios objective-c swift viewcontroller nsnotificationcenter

我想将表格单元格文本标签数据从swift类传递给目标c类。在快速课程中,我做了以下,

class NewsViewController: UIViewController, UITableViewDataSource, UITableViewDelegate {
@IBOutlet weak var newsTableView: UITableView!

var myVC:NewsDetailsViewController!
}

func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    tableView.deselectRow(at: indexPath, animated: true)
    print("selected index :",indexPath.row)

    let selectedCell = tableView.cellForRow(at: indexPath)
    print("did select and the text is \(selectedCell?.textLabel?.text)")
    myVC.passedValue = selectedCell?.textLabel?.text
    print("text label value: ", myVC.passedValue)
    NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PostQuestion"), object: myVC.passedValue)
    self.present(myVC, animated: true , completion: nil)

}

现在我想用另一个控制器接收这个字符串数据,这是一个客观的c类。请指导。

1 个答案:

答案 0 :(得分:4)

您应该通过

发送通知
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "PostQuestion"), 
    object: self,
    userInfo: ["value": myValue] as Dictionary<AnyHashable, Any>)

并使用类似

的方式处理通知
func processNotification(notification: NSNotification) {
    let userInfo = notifcation.userInfo

    if let value = userInfo?["value"] as? String {
        ...
    }
}

或在Objective-C中相同

- (void)processNotification:(NSNotification *)notification {
    NSString *value = [notifcation.userInfo objectForKey:@"value"]

    if(value) {
        ...
    }
}