NSKeyedUnarchiver不使用Swift 3

时间:2016-09-15 21:30:11

标签: swift xcode swift3 nskeyedunarchiver

我有以下代码用于在Mac应用程序中取消归档文件:

func tryOpen(_ filePath: String) throws -> NSArray {
    if #available(OSX 10.11, *) {
        do {
            if let data = try? Data(contentsOf: URL(fileURLWithPath: filePath)) {
                let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data) as! NSArray
                return array
            } else {
                throw NSError(domain: NSExceptionName.invalidUnarchiveOperationException.rawValue, code: 0, userInfo: nil)
            }
        } catch let ex {
            throw ex
        }
    } else {
        // Fallback on earlier versions
        let dat = try? Data(contentsOf: URL(fileURLWithPath: filePath))
        let unarchiver = NSKeyedUnarchiver(forReadingWith: dat!)
        if let array = unarchiver.decodeObject(forKey: "root") as? NSArray {
            return array
        } else {
            throw NSException(name: NSExceptionName.invalidArgumentException, reason: "Unable to unarchive file", userInfo: nil) as! Error
        }
    }
}

但是,自从我在Xcode 8.0中升级到Swift 3后,我出现以下错误消息: 'unarchiveTopLevelObjectWithData' is unavailable in Swift: Use 'unarchiveTopLevelObjectWithData(_:) throws' instead,这几乎是一回事,对吧?所以我对如何解决这个问题感到非常困惑。这是Xcode中的错误吗?

1 个答案:

答案 0 :(得分:10)

NSKeyedUnarchiver仍然期待NSData

let array = try NSKeyedUnarchiver.unarchiveTopLevelObjectWithData(data as NSData) as! NSArray

这已在Swift 4中得到纠正