如何从继承自nsobject和nscoding的类创建singleton类?

时间:2016-02-11 14:11:06

标签: swift sprite-kit singleton

我正在尝试制作加载,保存并使其成为单身类的游戏设置。我所有的努力都导致了失败,XCode问我“无法为没有参数的”类型“设置”调用初始化程序。我该如何解决这个问题?

这是代码:

class Settings: NSObject, NSCoding {

static let sharedInstance = Settings()

var currentLevel: Int
var positionOfPlayer: [Int]?
var sounds: Bool
var shape: String
var completedLevels: [Int: Bool]

init?(currentLevel: Int, positionOfPlayer: [Int]?, sounds: Bool, shape: String, completedLevels: [Int: Bool]) {
    self.currentLevel = currentLevel
    self.sounds = sounds
    self.shape = shape
    self.completedLevels = completedLevels

    if let position = positionOfPlayer as [Int]? {
        self.positionOfPlayer = position
    }

    super.init()
}

required convenience init?(coder aDecoder: NSCoder) {
    let currentLevel = aDecoder.decodeObjectForKey(SettingNames.nameOfCurrentLevel) as? Int
    let completedLevels = aDecoder.decodeObjectForKey(SettingNames.nameOfCompletedLevels) as? [Int: Bool]
    let positionOfPlayer = aDecoder.decodeObjectForKey(SettingNames.positionOfPlayerOnCurrentLevel) as? [Int]
    let sounds = aDecoder.decodeObjectForKey(SettingNames.nameOfSounds) as? Bool
    let shape = aDecoder.decodeObjectForKey(SettingNames.nameOfShapes) as? String
    self.init(currentLevel: currentLevel!, positionOfPlayer: positionOfPlayer, sounds: sounds!, shape: shape!, completedLevels: completedLevels!)
}

func encodeWithCoder(aCoder: NSCoder) {
    aCoder.encodeObject(currentLevel, forKey: SettingNames.nameOfCurrentLevel)
    aCoder.encodeObject(completedLevels, forKey: SettingNames.nameOfCompletedLevels)
    if let position = positionOfPlayer as [Int]? {
        // If game canceled or ended during playing, it saves the current player position.
        // Next time, when player open the game, it will continue
        aCoder.encodeObject(position, forKey: SettingNames.positionOfPlayerOnCurrentLevel)
    }
    aCoder.encodeBool(sounds, forKey: SettingNames.nameOfSounds)
    aCoder.encodeObject(shape, forKey: SettingNames.nameOfShapes)
}

}

1 个答案:

答案 0 :(得分:0)

您尝试访问的构造函数不接受当前类未实现的参数。尝试重写init方法,该方法应该删除错误。

override init(){
   // some code
}

这是我尝试过的完整示例:

import Foundation

  class Settings : NSObject, NSCoding {

  static let sharedInstance = Settings()

  var a: String?
  var b: String?

    convenience init(a: String, b: String){
      self.init()
      self.a = a
      self.b = b
    }

  override init(){

  }

  required init?(coder aDecoder: NSCoder) {

  }

  func encodeWithCoder(aCoder: NSCoder) {

  }

}

只是一个观点:要求你传递参数以配置它的单身人士不再像单身人士那样行事。