gpt4 book ai didi

objective-c - 在混合语言项目中提取通知用户信息

转载 作者:可可西里 更新时间:2023-10-31 23:58:10 26 4
gpt4 key购买 nike

我正在从事一个混合语言项目,在 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

当然,在这个混合语言项目中,必须正确设置桥接 header (只需在其中添加#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包含由 NSSTring: NSData 构建的 NSDictionary , NSSTring: NSNumber , NSSTring: NSNumber而此命令 let userInfo = notification.userInfo as Dictionary<String, String>正在尝试转换为 Dictionary<String, String>

这会导致 fatal error 吗?

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

提前致谢

最佳答案

尝试这样做

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

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

关于objective-c - 在混合语言项目中提取通知用户信息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27421373/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com