我正在开发一个混合语言项目,在XCode 6中结合了Objective C和Swift。
在这个项目中,Singleton(Objective C)类发布一个通知,然后由ViewController(Swift)接收。
Singleton.h
#import <Foundation/Foundation.h>
NSString *const notificationString = @"notificationString";
@interface Singleton : NSObject
+ (id)sharedSingleton;
- (void)post;
@end
Singleton.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
,NSSTring: NSNumber
,NSSTring: NSNumber
构建的NSDictionary,而此命令let userInfo = notification.userInfo as Dictionary<String, String>
正在尝试转换为Dictionary<String, String>
这是否会导致致命错误?
在ViewController.swift
中,我应该怎么做才能“阅读”从notification.userInfo
发送的Singleton.m
传递的NSDictionary?
提前致谢
答案 0 :(得分:9)
尝试这样做
let userInfo = notification.userInfo as Dictionary<String, AnyObject>
如您所示,userInfo字典包含NSData,NSNUmber表示值。