You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift中如何通过CFArrayGetValueAtIndex访问AXUIElement属性名?

解决Swift中AXUIElement属性名数组的访问问题

首先,你之前的错误在于CFArrayGetValueAtIndex在Swift中返回的是UnsafeRawPointer!,不能直接用类型名强转成NSString/CFString,需要正确处理指针的类型绑定。这里提供两种简洁的解决方式:

方式一:直接桥接为Swift数组(推荐)

Core Foundation和Foundation类型在Swift中可以自动桥接,你可以直接把CFArray转成Swift的[String],这样就能像普通数组一样访问元素:

var attrNames: CFArray? = nil
AXUIElementCopyAttributeNames(element, &attrNames)

// 安全地转换并访问
if let attrNames = attrNames as? [String] {
    let targetAttrName = attrNames[index]
    // 使用targetAttrName
}

方式二:手动处理单个元素的指针转换

如果你需要单独处理某个索引的元素,可以通过指针绑定来获取正确的CFString实例:

var attrNames: CFArray? = nil
AXUIElementCopyAttributeNames(element, &attrNames)

guard let attrNames = attrNames else { return }
// 确保索引在有效范围内
guard index < CFArrayGetCount(attrNames) else { return }

let rawPointer = CFArrayGetValueAtIndex(attrNames, index)
// 将原始指针绑定到CFString类型
let cfString = rawPointer.assumingMemoryBound(to: CFString.self).pointee
// 转成Swift String使用
let attrName = String(cfString: cfString)

错误原因说明

你之前写的(NSString) CFArrayGetValueAtIndex(...)是Swift语法错误,因为(NSString)是类型,不是类型转换操作。而且CFArrayGetValueAtIndex返回的是指向元素的原始指针,必须先绑定到对应类型的指针,才能获取到实际的字符串对象。

内容的提问来源于stack exchange,提问作者Deron Johnson

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.14 13:52:13