Search code examples
iosobjective-cswiftviewcontrollernsnotificationcenter

how to pass string data from swift to objective c class using notification


I want to pass table cell text label data from swift class to objective c class. In swift class I did the following,

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)

}

Now I want to receive this string data with my another controller which is a objective c class. Kindly guide.


Solution

  • You should send your notification with

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

    and process the notifications it with something like

    func processNotification(notification: NSNotification) {
        let userInfo = notifcation.userInfo
    
        if let value = userInfo?["value"] as? String {
            ...
        }
    }
    

    or the same in Objective-C

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