从Unmanaged获取swift类型的值< AnyObject>,例如:ABRecordRef

y3bcpkx1  于 2023-06-28  发布在  Swift
关注(0)|答案(3)|浏览(144)

如何从Unmanaged<AnyObject>类型的对象中获取Swift类型的值?我的示例使用ABRecordRef
我正在创建一个联系人对象,以便在获得ABRecordRef后进行管理,但在从ObjC转换时遇到了问题。这是我的资料

init(recordRef: ABRecordRef) {
    if let firstName = ABRecordCopyValue(recordRef, kABPersonFirstNameProperty) {
        self.firstName = firstName

    }
}

如果是ObjC,我会这样做:

CFTypeRef firstNameRef = ABRecordCopyValue(recordRef, kABPersonFirstNameProperty);
if (firstNameRef) {
    self.firstName = (__bridge NSString *)firstNameRef;
}

我似乎找不到正确的组合向下/转换,所以任何帮助是赞赏。

tpxzln5u

tpxzln5u1#

由于在我解决之前没有人回答,我将在这里添加答案:

firstName.takeRetainedValue() as? String

如果你查看Unmanaged结构类型的头文件,你会发现:

/// Get the value of this unmanaged reference as a managed
/// reference and consume an unbalanced retain of it.
///
/// This is useful when a function returns an unmanaged reference
/// and you know that you're responsible for releasing the result.
func takeRetainedValue() -> T

所以,因为CFTypeRef在Swift中被转换为Unmanaged<AnyObject>
Unmanaged使用泛型来定义返回类型,声明如下:

Unmanaged<T>

我们的对象的类型是Unmanaged<AnyObject>,这意味着takeRetainedValue()将返回类型T,或者在我们的例子中,返回类型AnyObject。我使用可选的向下转换,因为我的属性firstNameString?类型。
您可以使用takeRetainedValue方法从Unmanaged对象中获取值。在基础API中,我猜它们大多数是Unmanaged<AnyObject>!类型,并且需要向下转换。通式似乎是:

var unmanagedObject: Unmanaged<AnyObject> = someFunctionThatReturnsAnUnmanagedObject()
var newValue: Type = unmanagedObject.takeRetainedValue as Type
zpf6vheq

zpf6vheq2#

import UIKit
import AddressBook

class ViewController: UIViewController {

lazy var addressBook: ABAddressBookRef = {
    var error: Unmanaged<CFError>?
    return ABAddressBookCreateWithOptions(nil, &error).takeRetainedValue() as ABAddressBookRef
}()

@IBAction func GetPeople(sender: UIButton) {
    var ab: ABAddressBookRef = addressBook

    switch ABAddressBookGetAuthorizationStatus(){
    case .Authorized:
        println("Authorized")
        readFromAddressBook(addressBook)
    case .Denied:
        println("Denied")
    case .Restricted:
        println("Restricted")
    case .NotDetermined:
        println("Not determined")
        ABAddressBookRequestAccessWithCompletion(addressBook,
            {[weak self] (granted: Bool, error: CFError!) in
                if granted {
                    let strongSelf = self!
                    println("Access is granted")
                    strongSelf.readFromAddressBook(strongSelf.addressBook)
                }
                else{
                    println("Access is not granted")
                }
        })
    default:
        break
    }
}

func readFromAddressBook(addressBook: ABAddressBookRef){
    let allPeople = ABAddressBookCopyArrayOfAllPeople(addressBook).takeRetainedValue() as NSArray

    for person:ABRecordRef in allPeople{
        if let firstName = ABRecordCopyValue(person, kABPersonFirstNameProperty) {
            if let lastName = ABRecordCopyValue(person, kABPersonLastNameProperty) {
                let ln:String = (lastName.takeRetainedValue() as? String) ?? ""
                let fn:String = (firstName.takeRetainedValue() as? String) ?? ""
                println("\(ln) - \(fn)")
            }
        }
    }
}

}

k97glaaz

k97glaaz3#

let obj = classType.perform(selector)
    if let obj = obj as? AnyObject {
        let pointer: UnsafeMutableRawPointer = Unmanaged<AnyObject>.passUnretained(obj).toOpaque()
        let valueBool: Bool = pointer.load(as: Bool.self)
        return valueBool
    }
    return false

相关问题