【问题标题】:Pointer casting with ARC使用 ARC 进行指针转换
【发布时间】:2011-12-10 23:52:37
【问题描述】:

ARC 让我很难接受以下演员阵容:

NSDictionary *attributes;
SecItemCopyMatching((__bridge CFDictionaryRef)keychainItemQuery, (CFTypeRef *)&attributes);

错误:ARC 不允许使用指向“CFTypeRef ”(又名“const void *”)的 Objective-C 指针的间接指针强制转换

【问题讨论】:

    标签: objective-c automatic-ref-counting


    【解决方案1】:

    问题是属性不应该是字典,它应该是 SecKeyRef 或 CFDataRef。然后将其转换回 NSData 以获取复制到其中的密码数据。

    像这样:

    CFDataRef attributes;
    SecItemCopyMatching((__bridge CFDictionaryRef)keychainItemQuery, (CFTypeRef *)&attributes);
    NSData *passDat = (__bridge_transfer NSData *)attributes;
    

    【讨论】:

    • 让 ik 工作的小调整:SecItemCopyMatching((__bridge CFDictionaryRef) keychainItemQuery, (CFTypeRef*) &attributes);
    • @mmvie 我对其进行了编辑以使其正常工作。感谢您指出小错误。
    • 我不同意“问题在于属性不应该是字典”。 CFTypeRef 中返回的内容取决于 keychainItemQuery 的构造方式(请参阅developer.apple.com/library/ios/documentation/Security/…)。如果您在答案中将 NSData 更改为 NSDictionary ,那么这也将修复引发的错误。您的修复工作作为对 SecItemCopyMatching 的调用现在直接使用 CFDataRef 并引入了 __bridge_transfer。
    【解决方案2】:

    当我们做类似的事情并使用上面的例子时,我们面临另一个问题:

    CFDataRef resultRef;
    OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary,
                   (CFTypeRef *)&resultRef);
    NSData* result = (__bridge_transfer NSData*)resultRef; 
    

    这将导致 EXEC_BAD_ACCESS,因为 resultRef 未设置为任何地址并指向内存的某个位置。

    CFDataRef resultRef = nil;
    

    这将修复错误。

    【讨论】:

    • 如果没有找到您的搜索,就会发生这种情况。
    • 这种情况在未找到该项目时发生(因为SecItemCopyMatching 不会为其第二个参数初始化任何数据,因为没有要返回的数据)。如果没有找到任何东西(即status 不是errSecSuccess),您不需要对resultRef 执行任何操作。
    【解决方案3】:

    需要将attributes改为&attributes

    CFDataRef attributes;
    SecItemCopyMatching((__bridge CFDictionaryRef) keychainItemQuery,  ( CFTypeRef*) &attributes);
    NSData* passDat=(__bridge_transfer NSData*) attributes;
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-02-10
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-12
      • 2014-08-13
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多