首页 > 解决方案 > 试图将指针投射到 ARC 下的指针

问题描述

我收到此编译器错误:

ARC 不允许将非 Objective-C 指针类型“void * _Nullable”隐式转换为“NSObject *__strong *”

当我尝试编译在 ARC 之前有效的旧代码时。实际代码在一个由数组驱动的循环中。这个片段只是代码的一个循环值,用于突出显示错误,没有多余的东西。

- (void)myCode
{
    NSDictionary *sDict; // I want the @{ @"key" : @"value" } to end up here

    // this is in a loop to set several dictionaries
    // vcValue is set from a controlling array, but ends up like this:
    NSValue *vcValue = [NSValue valueWithPointer:&sDict];
    NSObject **vcPointer = [vcValue pointerValue]; // <<-- generates the error
    *vcPointer = @{ @"key" : @"value" }; // for sDict
}

我正在使用 NSObject,因为基于控制数组的指针可能指向 NSDictionary 或 NSArray。在这个例子中,它指向一个字典。

定义 vcPointer 的正确方法是什么?

标签: iosxcodecastingautomatic-ref-counting

解决方案


如果你不知道它是 anNSDictionary *还是 an NSArray *,那么正确的类型是id.

NSDictionary *sDict;
NSValue *vcValue = [NSValue valueWithPointer:&sDict];
id __strong *vcPointer = (id __strong *)vcValue.pointerValue;
*vcPointer = @{ @"key": @"value" };

推荐阅读