提取混合语言项目中的通知用户信息



我正在做一个混合语言项目,在XCode 6中结合了Objective C和Swift。

在这个项目中,Singleton(Objective C)类发布一个通知,然后由ViewController(Swift)接收。

辛格尔顿

#import <Foundation/Foundation.h>
NSString *const notificationString = @"notificationString";
@interface Singleton : NSObject
+ (id)sharedSingleton;
- (void)post;
@end

辛格尔顿

#import "Singleton.h"
static Singleton *shared = nil;
@implementation Singleton
- (id)init {
    self = [super init];
    if (self) {
    }
    return self;
}
#pragma mark - Interface
+ (Singleton *)sharedSingleton {
    static dispatch_once_t pred;
    dispatch_once(&pred, ^{
        shared = [[Singleton alloc] init];
    });
    return shared;
}
- (void)post {
    char bytes[5] = {5, 7, 9, 1, 3};
    NSDictionary *objects = @{@"device":[NSData dataWithBytes:bytes length:5], @"step1":[NSNumber numberWithInt:4], @"step2":[NSNumber numberWithInt:7]};
    [[NSNotificationCenter defaultCenter] postNotificationName:notificationString
                                                        object:self
                                                      userInfo:objects];
}
@end

当然,在这个混合语言项目中,桥接标头必须正确设置(只需在其中添加#import "Singleton.h"即可)

视图控制器.swift

import UIKit
class ViewController: UIViewController {
    let singleton = Singleton.sharedSingleton() as Singleton
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "action:", name: notificationString, object: nil)
        singleton.post()
    }
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.

    }
    // MARK: - Notification
    func action(notification: NSNotification) {
        let userInfo = notification.userInfo as Dictionary<String, String> // things go wrong here?!
        let hash = userInfo["device"]
        let completed = userInfo["step1"]
        let total = userInfo["step2"] 
    }
}

这不会产生编译错误。但是,在运行时,XCode 报告:

致命错误:字典无法从 Objective-C 桥接

notification.userInfo包含一个由NSSTring: NSDataNSSTring: NSNumberNSSTring: NSNumber构建的NSDictionary,而这个命令let userInfo = notification.userInfo as Dictionary<String, String>正在尝试转换为Dictionary<String, String>

这会导致致命错误吗?

ViewController.swift中,我应该怎么做才能"读取"从Singleton.m发送的notification.userInfo传递的NSDictionary?

提前致谢

尝试这样做

let userInfo = notification.userInfo as Dictionary<String, AnyObject>

正如你所指出的,userInfo 字典包含 NSData、NSNUmber 作为值。

最新更新