EXC_BAD_ACCESS 声明变量时

EXC_BAD_ACCESS when declaring a variable

正如我所说,我在声明变量时遇到错误。我在 Google 和 Swift 文档上都找不到任何解决方案。 代码如下:

class Database {
static let si = Database() // when removed it also resolves into an error

init() {
    print("Hello") // isn't printed.
    self.setONs() // see code below to see where collected gets a new value
    print("current device id: \(UIDevice.current.identifierForVendor!.uuidString)") // resolves into an error when declared as uuid which is now "TestUID"
}

var uuid: String = "TestUID" // its actual the device id.
var gkid: String = "" // GKPlayerID
var collected: [String : [String : Int]] = [:] // <- Thread 1: EXC_BAD_ACCESS(code=2,address=0x7fff59de4f8)
private var collectedProgress: [String : [String : Int]] = [:]

如果我删除 collectedProgress,则在 collectedProgress 上会发生错误访问。这两个变量都只是声明,而不是写入或读取。即使我也删除了 collectedProgress 变量,下一个变量也会发生相同的错误。

您的两个变量 collected 和 collectedProgress 设置不正确。您已将 collected 声明为具有字符串键和值 [String:Int] 的字典,但您正试图使用​​ [Any:Any] 类型的字典对其进行初始化。我不确定为什么会编译。

尝试将您的代码更改为:

var collected = [String : [String : Int]]()
private var collectedProgress = [String : [String : Int]]()

使用该代码为这些变量创建初始值并让编译器自动计算出它们的类型数据类型。

您可能还想为您的 [String : [String : Int] 类型创建类型别名:

typealias DictOfDicts = [String : [String : Int]]

//...

var collected = DictOfDicts()
private var collectedProgress = DictOfDicts()

我解决了这个问题。我不是 100% 确定这是否是错误,但目前没有 EXC_BAD_ACCESS。 我在 Database() 中添加了一个 sharedInstance,并将其他 Classes/Objects 中的 Database() 替换为 Database.sharedInstance。现在所有对象都使用同一个对象。 数据库中的接收器 ( SocketIOManager.sharedInstance.on("") {}) 可能是问题所在。由于他们收到了变量的新值等等,但是正如他们评论的那样,错误也发生了。 我希望你不会得到与我用你的代码得到的相同的 error/problem。

也感谢您的帮助。

Fixed code on Github