2

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

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

单例.h

#import <Foundation/Foundation.h>

NSString *const notificationString = @"notificationString";

@interface Singleton : NSObject

+ (id)sharedSingleton;

- (void)post;

@end

单身人士.m

#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"

ViewController.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: NSData,构建的 NSDictionary NSSTring: NSNumberNSSTring: NSNumber而此命令let userInfo = notification.userInfo as Dictionary<String, String>正在尝试转换为Dictionary<String, String>

这会导致致命错误吗?

ViewController.swift中,我应该怎么做才能“读取”传入的 NSDictionary notification.userInfo,发送自Singleton.m

提前致谢

4

1 回答 1

9

尝试这样做

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

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

于 2014-12-11T11:11:19.350 回答