数组 – 在Swift中使用NSCoding的可选结构的归档数组?
发布时间:2020-12-14 05:53:26 所属栏目:百科 来源:网络整理
导读:我在Obj-C中做了很多NSCoding归档,但是我不知道如何处理Swift中的结构体,也不知道如何处理Swift中的结构体,也不知道如何处理Swift中的结构体。这是我的代码: public struct SquareCoords { var x: Int,y: Int} 这里是我需要存储的课程: public class Pl
我在Obj-C中做了很多NSCoding归档,但是我不知道如何处理Swift中的结构体,也不知道如何处理Swift中的结构体,也不知道如何处理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") } ... 在编码器init的最后一行,我在XCode中收到以下错误消息: 'AnyObject' is not convertible to [SquareCoords?]' 并在编码的最后一行: Extra argument 'forKey' in call 任何人都可以让我朝着正确的方向前进吗?
我不知道确切的问题是什么,但如果您使用NSMutableArray而不是Swift数组,问题解决:
public struct SquareCoords { var x: Int,y: Int } public class Player: NSCoding { var playerNum: Int var name = "" var moveHistory: NSMutableArray = NSMutableArray() 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 NSMutableArray } public func encodeWithCoder(aCoder: NSCoder!) { aCoder.encodeInteger(playerNum,forKey: "moveHistoryKey") } } 似乎是这样的情况,当aDecoder.decodeObjectForKey返回一个隐式解开的AnyObject时,它不会转换为一个SquareCoords数组。 玩了一点,我注意到它可能与使用结构有关。 (你正在创建一个值类型的结构体数组。)这是一个猜测,但是我注意到,如果一个类类型用于SquareCoords,那就没有问题,例如 public class SquareCoords { var x: Int = 0,y: Int = 0 } public class Player: NSCoding { var playerNum: Int var name = "" private var moveHistory: [SquareCoords] = [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") } } 也许由于某种原因,AnyObject的转换不会导致一个struct数组。 – 我相信别人可以提供更多的见解,希望这有所帮助!斯威夫特可以是暴风雨的:D (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |