Objective c 在混合语言项目中提取通知userinfo
我正在从事一个混合语言项目,将Objective C和Swift结合到XCode 6中 在这个项目中,Singleton(Objective C)类发布一个通知,然后由ViewController(Swift)接收 辛格尔顿Objective c 在混合语言项目中提取通知userinfo,objective-c,swift,notifications,xcode6,userinfo,Objective C,Swift,Notifications,Xcode6,Userinfo,我正在从事一个混合语言项目,将Objective C和Swift结合到XCode 6中 在这个项目中,Singleton(Objective C)类发布一个通知,然后由ViewController(Swift)接收 辛格尔顿 #import <Foundation/Foundation.h> NSString *const notificationString = @"notificationString"; @interface Singleton : NSObject +
#import <Foundation/Foundation.h>
NSString *const notificationString = @"notificationString";
@interface Singleton : NSObject
+ (id)sharedSingleton;
- (void)post;
@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"]
}
}
导入UIKit
类ViewController:UIViewController{
设singleton=singleton.sharedSingleton()为singleton
重写func viewDidLoad(){
super.viewDidLoad()
//加载视图后,通常从nib执行任何其他设置。
NSNotificationCenter.defaultCenter().addObserver(self,选择器:“操作:”,名称:notificationString,对象:nil)
singleton.post()
}
重写函数didReceiveMemoryWarning(){
超级。我收到了记忆警告()
//处置所有可以重新创建的资源。
}
//马克:-通知
func操作(通知:NSNotification){
让userInfo=notification.userInfo作为字典//这里出了问题?!
让hash=userInfo[“设备”]
let completed=userInfo[“步骤1”]
让总数=用户信息[“步骤2”]
}
}
这不会导致编译错误。但是,在运行时,XCode报告:
致命错误:无法从Objective-C桥接字典
notification.userInfo
包含由NSSTring:NSData
、NSSTring:NSNumber
、NSSTring:NSNumber
构建的NSDictionary,而此命令让userInfo=notification.userInfo作为Dictionary
尝试转换为Dictionary
这会导致致命错误吗
在ViewController.swift
中,如何“读取”从Singleton.m
发送的notification.userInfo
中传递的NSDictionary
提前谢谢试试看
let userInfo = notification.userInfo as Dictionary<String, AnyObject>
让userInfo=notification.userInfo作为字典
正如您所指出的,userInfo字典包含NSData,NSNUmber表示值。FWIW,我的代码中有dictionary
,但效果也不太好<显然,code>AnyObject不应标记为可选。
let userInfo = notification.userInfo as Dictionary<String, AnyObject>