用ARC指针铸造

mmv*_*vie 29 objective-c automatic-ref-counting

ARC让我很难跟随演员:

NSDictionary *attributes;
SecItemCopyMatching((__bridge CFDictionaryRef)keychainItemQuery, (CFTypeRef *)&attributes);
Run Code Online (Sandbox Code Playgroud)

错误:ARC不允许使用指向'CFTypeRef '(又名'const void* ')的Objective-C指针的间接指针

uta*_*hak 41

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

像这样:

CFDataRef attributes;
SecItemCopyMatching((__bridge CFDictionaryRef)keychainItemQuery, (CFTypeRef *)&attributes);
NSData *passDat = (__bridge_transfer NSData *)attributes;
Run Code Online (Sandbox Code Playgroud)

  • 使ik工作的小调整:SecItemCopyMatching((__ bridge CFDictionaryRef)keychainItemQuery,(CFTypeRef*)&attributes); (6认同)

小智 6

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

CFDataRef resultRef;
OSStatus status = SecItemCopyMatching((__bridge CFDictionaryRef)searchDictionary,
               (CFTypeRef *)&resultRef);
NSData* result = (__bridge_transfer NSData*)resultRef; 
Run Code Online (Sandbox Code Playgroud)

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

CFDataRef resultRef = nil;
Run Code Online (Sandbox Code Playgroud)

这将解决错误.