Я работаю над проектом смешанного языка, сочетающий в себе как Objective C и Swift в XCode 6.Extract уведомление USERINFO в смешанном языке проекта
В этом проекте 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:
fatal error: dictionary cannot be bridged from 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
?
Заранее спасибо
Он отлично работает! Большое спасибо – quanguyen
FWIW, у меня был «Словарь» В моем коде, и это тоже не сработало. По-видимому, 'AnyObject' не должен быть помечен как необязательный. –
Romain