在 Swift 中使用 NSCoding 归档可选结构数组?

2024-05-27

我已经在 Obj-C 中完成了大量 NSCoding 归档,但我不确定它如何处理 Swift 中的结构,也不确定它如何处理具有可选值的数组。这是我的代码:

public struct SquareCoords {
    var x: Int, y: Int
}

这是我需要存储的类:

public class Player: NSCoding {
    var playerNum: Int
    var name = ""
    private var moveHistory: [SquareCoords?] = []

    init (playerNum: Int, name: String) {
        self.playerNum = playerNum
        self.name = name
    }

    public required init(coder aDecoder: NSCoder!) {
        playerNum = aDecoder.decodeIntegerForKey("playerNumKey")
        name = aDecoder.decodeObjectForKey("nameKey") as String
        moveHistory = aDecoder.decodeObjectForKey("moveHistoryKey") as [SquareCoords?]
    }

    public func encodeWithCoder(aCoder: NSCoder!) {
        aCoder.encodeInteger(playerNum, forKey: "playerNumKey")
        aCoder.encodeObject(name, forKey: "nameKey")
        aCoder.encodeObject(moveHistory, forKey: "moveHistoryKey")
    }
...

在 coder init 的最后一行,我在 XCode 中收到以下错误消息:

'AnyObject' is not convertible to [SquareCoords?]'

在encodeWithEncoder的最后一行:

Extra argument 'forKey' in call

谁能让我朝着正确的方向前进?


In Swift 编程语言 https://developer.apple.com/library/ios/documentation/swift/conceptual/swift_programming_language/TypeCasting.html,苹果表示:

Swift 提供了两个特殊类型别名来处理非特定类型:
- AnyObject可以表示任何类类型的实例。
- Any可以表示任何类型的实例,包括函数类型。

知道这一点后,输入SquareCoords(Swift 结构)和类型[SquareCoords](Swift结构的Swift数组)无法符合协议AnyObject.

另一方面,decodeObjectForKey:需要一个符合协议的参数AnyObject, and encodeObject:forKey:回报AnyObject。因此,以下两行无法编译:

moveHistory = aDecoder.decodeObjectForKey("moveHistoryKey") as [SquareCoords?]
aCoder.encodeObject(moveHistory, forKey: "moveHistoryKey")

因此,除非你找到一种方法SquareCoords符合协议AnyObject(不知道可不可以),你必须转型SquareCoords从 Swift 结构到类。

PS:此时,您可能会问:“好吧,但是怎么可能输入String- 这实际上是一个 Swift Struct - 可以符合协议AnyObject?”嗯,那是因为String与基金会无缝连接NSString class (Array, Dictionary桥接到NSArray and NSDictionary一样的方法)。读这篇博文 http://www.drewag.me/posts/swift-s-weird-handling-of-basic-value-types-and-anyobject如果你想更好地了解它。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

在 Swift 中使用 NSCoding 归档可选结构数组? 的相关文章

随机推荐