objective-c - objective-c 类和 swift 类之间的 NSNotification

标签 objective-c swift nsnotificationcenter nsnotifications

我的项目同时包含 objective-c 类和 swift 类。现在我需要从 Objective-C 类发布通知:

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {

    // Here I present swift view controller
    CollectionViewController *cvc = [[CollectionViewController alloc] initWithNibName:@"CollectionViewController" bundle:nil];
    UINavigationController *controller = [[UINavigationController alloc] initWithRootViewController:cvc];
    [self.navigationController presentViewController:controller animated:YES completion:nil];

    [[NSNotificationCenter defaultCenter] postNotificationName:@"BuildingReady" object:self userInfo:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:chosenBuilding, nil] forKeys:[NSArray arrayWithObjects:@"chosenBuilding", nil]]];
}

我正在 swift 类中收听此通知:

import UIKit

@objc class CollectionViewController : UIViewController, UICollectionViewDataSource, UICollectionViewDelegate , UICollectionViewDelegateFlowLayout {

   override func viewDidLoad() {
      super.viewDidLoad()

      NSNotificationCenter.defaultCenter().addObserver(self, selector: "getBuilding:", name: "BuildingReady", object: nil)
   }

   func getBuilding(notification: NSNotification) {
        let userInfo: Dictionary<String, Building!> = notification.userInfo as! Dictionary<String, Building!>

        self.chosenBuilding = userInfo["chosenBuilding"]
   }

问题是在 swift 类中我从来没有收到通知(func getBuilding 从未被调用)。 一个对象是 objective-c 类而第二个对象是 swift 类会不会有问题?

最佳答案

尝试这样的事情:

dispatch_async(dispatch_get_main_queue(), ^{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"BuildingReady" object:self userInfo:[NSDictionary dictionaryWithObjects:[NSArray arrayWithObjects:choosedBuilding, nil] forKeys:[NSArray arrayWithObjects:@"choosedBuilding", nil]]];
});

关于objective-c - objective-c 类和 swift 类之间的 NSNotification,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29795515/

相关文章:

ios - 在 iOS 8.1 中将整个应用程序的 View 旋转锁定为横向

objective-c - NSNotification 或 Delegate 以在可见 View 更改时进行注册

ios - 在 Objective-C 中共享数据对象的最佳方式是什么?

swift - 在 swift 脚本中指定 swift 解释器版本

ios - keyboardWillShow 被其他应用程序的键盘调用

ios - RestKit相同路径的多个响应描述符

swift - HKQuantity 翻倍 - 从 Healthkit 获得 active 能量值

快速守护 self

ios - 在 View 之间发送 NSNotification

macos - 不再需要删除 Cocoa 中的通知观察者?