Han*_*ans 1 c++ enums objective-c swift
我想将 userInfo 数据从 NSNotification 转换为枚举以在 switch 语句中使用。该通知来自预编译的 C++ 框架,其中包含一些定义 te 枚举的头文件。
-(void)updateOTAStatus:(NSNotification *)notification {
NSDictionary *userInfo = notification.userInfo;
otaUpgradeStatus status = (otaUpgradeStatus)userInfo[@"status"];
//...
}
Run Code Online (Sandbox Code Playgroud)
枚举定义:
typedef NS_ENUM(NSUInteger, otaUpgradeStatus) {
none = 0,
started = 1,
inProgress = 2,
completed = 3,
failed = 4,
failedLowBattery = 5,
cancelled = 6,
timedout = 7,
forced = 8
};
Run Code Online (Sandbox Code Playgroud)
调试时我得到
Printing description of status:
(otaUpgradeStatus) status = 6178538944
Run Code Online (Sandbox Code Playgroud)
当我在 Swift 中执行相同操作时, switch 语句失败:
let status = notification.userInfo?["status"] as? otaUpgradeStatus
Run Code Online (Sandbox Code Playgroud)
我得到了正确的状态,并且 switch 语句按预期工作。
这里出了什么问题?
AnNSDictionary只能保存对象,即(的子类)的实例NSObject。Swift 有一种机制可以_SwiftValue透明地包装/解开不透明实例中的值。
但为了与 Objective-C 互操作,您必须将数字作为NSNumber实例放入 Swift 端的用户信息字典中,例如
let notification = Notification(name: ..., object: ...,
userInfo: ["status": NSNumber(value: otaUpgradeStatus.failed.rawValue)])
Run Code Online (Sandbox Code Playgroud)
并在 Objective-C 端提取整数值,例如
NSDictionary *userInfo = notification.userInfo;
NSNumber *num = userInfo[@"status"];
otaUpgradeStatus status = num.unsignedIntegerValue;
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
409 次 |
| 最近记录: |