我的项目同时包含 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/