NSCopy GKGameModel 无法正确复制播放器对象



我正在尝试使用swift NSCopy来做GKGameModel对象的深度复制,包括所有玩家和他们的钱包参考(包含代表他们现金的整数(。

使用 Swift 游乐场,我尝试将所有复制的玩家记入 100 美元,但保留原始玩家对象不变。

但是,我注意到代码也会影响原始播放器对象。

在高级别上,代码应显示:

Game class, a GKGameModel
Player class, a GKPlayerModel
Wallet class, handles very basic player's Int transactions.

目标:

  • 复制游戏类、所有玩家及其关联的钱包类
  • 将 100 美元记入复制的玩家。
  • 原始玩家应该仍然有 0 美元

代码如下:

// Uses Swift playground
import GameplayKit
class Game : NSObject, GKGameModel{
override var description: String {
return ("game: (String(describing: self.players))")
}
// -- GKGameModel code follows --
var players: [GKGameModelPlayer]?
var activePlayer: GKGameModelPlayer?

func gameModelUpdates(for player: GKGameModelPlayer) -> [GKGameModelUpdate]? {
return nil
}
func unapplyGameModelUpdate(_ gameModelUpdate: GKGameModelUpdate) {
}

func apply(_ gameModelUpdate: GKGameModelUpdate) {
}
func setGameModel(_ gameModel: GKGameModel) {
guard let inputModel = gameModel as? Game else {
assertionFailure("No game model initialised")
return
}
guard let players = inputModel.players else {
assertionFailure("No players initialised")
return
}
self.activePlayer = inputModel.activePlayer
self.players = players
}
func copy(with zone: NSZone? = nil) -> Any {
print ("copying game obj!")
let copy = Game()
copy.setGameModel(self)
copy.players = self.players  // if I do not include it, copy.players is nil
return copy
}
}
class Player : NSObject, NSCopying, GKGameModelPlayer {
override var description: String {
return ("name: (name), cash: $(cash), wallet: $(wallet.balance)")
}
internal var playerId: Int = 0 {
didSet {
print ("Set playerId = (self.playerId)")
}
}
var name: String
var cash : Int = 0
var wallet : Wallet = Wallet()
init(name: String) {
self.name = name
}
func copy(with zone: NSZone? = nil) -> Any {
print ("copying player!!") // this code is never reached
let copy = self
copy.wallet = self.wallet.copy(with: zone) as! Wallet
return copy
}
}
enum WalletError : Error {
case mustBePositive
case notEnoughFunds
}
fileprivate protocol WalletDelegate {
var balance : Int { get }
func credit(amount: Int) throws
func debit(amount: Int) throws
}
class Wallet : NSCopying, CustomStringConvertible, WalletDelegate {
public private(set) var balance: Int = 0
func credit(amount: Int = 0) throws {
try canCredit(amount: amount)
self.balance += amount
}
func debit(amount: Int = 0) throws {
try canDebit(amount: amount)
self.balance -= amount
}
func copy(with zone: NSZone? = nil) -> Any {
print ("copy wallet")  // this code is never reached
let copy = Wallet()
return copy
}
}

extension Wallet {
private func canCredit(amount: Int) throws {
guard amount > 0 else {
throw WalletError.mustBePositive
}
}
private func canDebit(amount: Int) throws {
guard amount > 0 else {
throw WalletError.mustBePositive
}
guard self.balance >= amount else {
throw WalletError.notEnoughFunds
}
guard (self.balance - amount >= 0) else {
throw WalletError.notEnoughFunds
}
}
}
extension Wallet {
var description: String {
return ("Balance: $(self.balance)")
}
}
let players : [GKGameModelPlayer] = [ Player.init(name: "Bob"), Player.init(name: "Alex"), Player.init(name: "John")  ]
let game = Game()
game.players = players
func copyTheGame() {
let copiedGame = game.copy() as! Game
print ("BEFORE:")
print ("Original: (String(describing: game))")
print ("Copied: (String(describing: copiedGame))")
print ("----")
if let copiedPlayers = copiedGame.players {
for p in copiedPlayers as! [Player] {
do {
p.cash = 100 // try to manipulate a class variable.
try p.wallet.credit(amount: 100)
} catch let err {
print (err.localizedDescription)
break
}
}
}
print ("AFTER:")
print ("Original: (String(describing: game))")
print ("Copied: (String(describing: copiedGame))")
print ("----")
}
copyTheGame()

在我的输出中,我得到以下内容:

copying game obj!
BEFORE:
Original: game: Optional([name: Bob, cash: $0, wallet: $0, name: Alex, cash: $0, wallet: $0, name: John, cash: $0, wallet: $0])
Copied: game: Optional([name: Bob, cash: $0, wallet: $0, name: Alex, cash: $0, wallet: $0, name: John, cash: $0, wallet: $0])
----
AFTER:
Original: game: Optional([name: Bob, cash: $100, wallet: $100, name: Alex, cash: $100, wallet: $100, name: John, cash: $100, wallet: $100])
Copied: game: Optional([name: Bob, cash: $100, wallet: $100, name: Alex, cash: $100, wallet: $100, name: John, cash: $100, wallet: $100])
----

问题:

  • 播放器复制代码永远不会被命中
  • 钱包复制代码永远不会被击中
  • 贷记的 100 美元会影响原件和副本。

如何确保我所做的任何更改仅针对复制的游戏对象,而不是原始对象?

致谢


更新:

我已经能够通过遍历所有播放器对象来强制复制,但我不相信这是最好的方法。

如果我将游戏类中的复制函数更改为:

func copy(with zone: NSZone? = nil) -> Any {
let copy = Game()
let duplicate = self.players?.map({ (player: GKGameModelPlayer) -> GKGameModelPlayer in
let person = player as! Player
let copiedPlayer = person.copy(with: zone) as! Player
return copiedPlayer
})
copy.players = duplicate
return copy
}

这也让我复制了所有播放器对象;播放器和钱包类中的copy((函数被击中。

我已经能够通过强制复制引用对象、数组或子对象来解决此问题

即:

func copy(with zone: NSZone? = nil) -> Any {
let copy = Game()
let duplicate = self.players?.map({ (player: GKGameModelPlayer) -> GKGameModelPlayer in
let person = player as! Player
let copiedPlayer = person.copy(with: zone) as! Player
return copiedPlayer
})
copy.players = duplicate
return copy
}

相关内容

  • 没有找到相关文章

最新更新