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

Objective-C转Swift:书签数据属性提取遇阻求助

Objective-C转Swift:书签数据属性提取解决方案

下面是对应你提供的Objective-C代码的Swift转换版本,重点解决从书签数据中提取属性的核心问题:

func extractItems(at path: String) -> [Item] {
    guard let data = NSDictionary(contentsOfFile: path) as? [String: Any] else {
        return []
    }
    var items = [Item]()
    
    for object in data["$objects"] as? [Any] ?? [] {
        var bookmarkData: Data? = nil
        
        // 提取书签数据
        if let dataObject = object as? Data {
            bookmarkData = dataObject
        } else if let dict = object as? [String: Any] {
            bookmarkData = dict["NS.data"] as? Data
        }
        
        guard let bookmark = bookmarkData else {
            continue
        }
        
        // 核心:从书签数据提取所有属性
        guard let resourceValues = try? URL.resourceValues(forKeys: [.bookmarkAllPropertiesKey], fromBookmarkData: bookmark),
              let properties = resourceValues[.bookmarkAllPropertiesKey] as? [String: Any] else {
            continue
        }
        
        // 创建Item实例
        let item = Item()
        item.path = path
        item.executable = properties["_NSURLPathKey"] as? String
        item.type = NSNumber(value: ItemType.rawValue) // 若ItemType是Objective-C枚举直接用ItemType即可
        item.user = extractUserFromPath(path)
        item.content = nil
        
        // 获取名称:优先取Bundle的CFBundleName,否则用书签属性中的NSURLNameKey
        if let executablePath = item.executable,
           let bundle = Bundle(path: executablePath),
           let bundleName = bundle.infoDictionary?["CFBundleName"] as? String,
           !bundleName.isEmpty {
            item.name = bundleName
        } else {
            item.name = properties["NSURLNameKey"] as? String
        }
        
        // 校验必要属性,不满足则跳过
        guard item.name != nil, item.executable != nil else {
            continue
        }
        
        items.append(item)
    }
    
    return items
}

核心难点解析

  1. 书签属性提取的Swift对应写法
    Objective-C中的[NSURL resourceValuesForKeys:@[@"AllPropertiesKey"] fromBookmarkData:bookmark][@"AllPropertiesKey"],在Swift中对应:

    • 使用URL.resourceValues(forKeys: [.bookmarkAllPropertiesKey], fromBookmarkData: bookmark)获取资源值集合
    • 通过resourceValues[.bookmarkAllPropertiesKey]取出所有属性的字典,再转换为[String: Any]类型(对应原Objective-C的NSDictionary)
  2. 关键细节注意

    • Swift中该方法会抛出错误,因此用try?处理可选结果,也可根据需求改用do-catch捕获错误做更精细处理
    • 原Objective-C中的_NSURLPathKey和NSURLNameKey是底层字符串键,Swift中无对应枚举,直接用字符串访问即可
    • 所有可选值都做了安全解包,避免强制解包导致崩溃

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.13 08:28:35