gpt4 book ai didi

swift - 如何从继承 nsobject 和 nscoding 的类创建单例类?

转载 作者:行者123 更新时间:2023-11-30 13:42:59 25 4
gpt4 key购买 nike

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

这是代码:

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)
}

}

最佳答案

您正在尝试访问一个不接受当前类未实现的参数的构造函数。尝试重写 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) {

}

}

只是一个观点:需要传递参数才能配置的单例不再表现得像单例。

关于swift - 如何从继承 nsobject 和 nscoding 的类创建单例类?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35341600/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com