qua*_*yen 2 notifications objective-c userinfo swift xcode6
我正在开发一个混合语言项目,在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
Run Code Online (Sandbox Code Playgroud)
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
Run Code Online (Sandbox Code Playgroud)
当然,在这个混合语言项目中,必须正确设置桥接头(只需添加#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"]
}
}
Run Code Online (Sandbox Code Playgroud)
这不会导致编译错误.但是,在运行时,XCode报告:
致命错误:无法从Objective-C桥接字典
notification.userInfo包含一个NSDictionary由建NSSTring: NSData,NSSTring: NSNumber,NSSTring: NSNumber而此命令let userInfo = notification.userInfo as Dictionary<String, String>试图转换为Dictionary<String, String>
这会导致致命错误吗?
在ViewController.swift,我应该做什么来"读取"传入的NSDictionary notification.userInfo,从Singleton.m?
提前致谢
试着这样做
let userInfo = notification.userInfo as Dictionary<String, AnyObject>
Run Code Online (Sandbox Code Playgroud)
如您所示,userInfo字典包含NSData,NSNUmber表示值.
| 归档时间: |
|
| 查看次数: |
1177 次 |
| 最近记录: |