2015-07-21 56 views
7

在Xcode中6和7斯威夫特以前的版本,這個語法將工作:如何在Xcode 7 beta 4中調用SecItemCopyMatching?

var secureItemValue: Unmanaged<AnyObject>? 

    let statusCode: OSStatus = SecItemCopyMatching(keychainItemQuery, &secureItemValue) 
    if statusCode == errSecSuccess 
    { 
     let opaquePointer = secureItemValue?.toOpaque() 

     let secureItemValueData = Unmanaged<NSData>.fromOpaque(opaquePointer!).takeUnretainedValue() 

     // Use secureItemValueData... 
    } 

然而,SecItemCopyMatching聲明已在Xcode改變7 beta 4版本:

OLD:func SecItemCopyMatching(_ query: CFDictionary, _ result: UnsafeMutablePointer<AnyObject?>) -> OSStatus

NEW :func SecItemCopyMatching(_ query: CFDictionary!, _ result: UnsafeMutablePointer<Unmanaged<AnyObject>?>) -> OSStatus

...現在secureItemValue類型不匹配。

該機制之前提取結果令人困惑,我希望它在某種程度上更容易與新的聲明,但我不知道如何聲明secureItemValue變量的正確類型並提取結果。

回答

16

這部作品的Xcode 7 beta 4版本

var dataTypeRef: AnyObject? 

    let status: OSStatus = withUnsafeMutablePointer(&dataTypeRef) { SecItemCopyMatching(keychainQuery as CFDictionaryRef, UnsafeMutablePointer($0)) } 

    if status == noErr { 
     return dataTypeRef as? NSData 
    } 
    else { 
     return nil 
    } 
+1

尼斯,@Maximilian。在一百萬年內不會想到這件事! – Daniel

+0

如果一個對象是可選的,它的默認值爲nil,所以'var dataTypeRef:AnyObject?'和'var dataTypeRef:AnyObject? = nil'完全相同 – Maximilian

+0

是的馬克西米利安你是對的,我要刪除我的評論。 – Neil

4

根據this answer你可以刪除Unmanaged<>各地AnyObject:

var secureItemValue: AnyObject? 

let statusCode: OSStatus = SecItemCopyMatching(keychainItemQuery, &secureItemValue)