【问题标题】:Prevent takeRetainedValue or takeUnretainedValue when using an Objective-C Struct使用 Objective-C 结构时防止 takeRetainedValue 或 takeUnretainedValue
【发布时间】:2016-10-28 15:35:03
【问题描述】:

我使用this approach 将我的字符串常量放在一起。使用该帖子中的相同示例:

MONExtResult.h

struct MONExtResultStruct {
    __unsafe_unretained NSString * const AppID;
    __unsafe_unretained NSString * const ErrorCode;
    __unsafe_unretained NSString * const Progress;
};

extern const struct MONExtResultStruct MONExtResult;

MONExtResult.m

const struct MONExtResultStruct MONExtResult = {
    .AppID = @"appid",
    .ErrorCode = @"errorcode",
    .Progress = @"progress"
};

这可以像这样在 Objective-C 中使用:

NSString *str = MONExtResult.AppID;

当我尝试在 Swift 中使用它时:

let appID: String = MONExtResult.AppID

...我收到错误:

无法转换“Unmanaged!”类型的值到预期的参数类型“字符串”

这是因为我需要从unmanaged wrapper 中获取值,然后将其转换为字符串:

let appID: String = MONExtResult.AppID.takeUnretainedValue() as String

是否有任何方法可以注释 Objective-C 代码以防止需要调用 takeUnretainedValue,就像使用 CF_IMPLICIT_BRIDGING_ENABLEDCF_RETURNS_RETAINED 调用 C 函数一样?

更新: 常量必须可以被 Objective-C 和 Swift 访问。否则我只会使用带有 String 原始值的 Swift 枚举。

【问题讨论】:

    标签: objective-c c swift memory-management automatic-ref-counting


    【解决方案1】:

    我能够构建的最接近的是:

    enum MONExtResult: String {
        case AppID = "com.me.myapp"
        case ErrorCode = "game over"
        case Progress = "vote Tuesday"
    }
    
    extension String {
        init(const: MONExtResult) {
            self = const.rawValue
        }
    }
    
    let err = String(MONExtResult.ErrorCode)
    

    值得注意的是,这不起作用:

    let appID: String = MONExtResult.AppID
    

    因为末尾缺少 .rawValue,但只要您愿意接受大致相同数量的字符和稍微不同的语法,我相信这就是您的想法。

    【讨论】:

    • 其中一个要求是它必须保持为 Objective-C 结构,因为我需要在 Objective-C 和 Swift 中都使用它。如果我在 Swift 中创建枚举,由于原始值,它无法在 Objective-C 代码中访问。
    • 请给我一个你想如何使用Objective-C的例子
    • 另外,如果你简单地消除所有不安全的未保留注释会发生什么?
    • 我更新了示例以展示它在 Objective-C 中的使用方式 (MONExtResult.AppID)。
    猜你喜欢
    • 2017-11-26
    • 2022-09-23
    • 2015-05-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-10-22
    • 1970-01-01
    相关资源
    最近更新 更多