我一直在使用Xcode中的Swift编程语言,我相信我遇到了一个错误,只是我不完全确定。当我编译并运行以下程序时:
import Foundation typealias GeneratorCallback = () -> AnyObject? typealias NamedGenerators = [String: GeneratorCallback] var generators = NamedGenerators() class ValueResetter { let name: String let originalValue: AnyObject? init(name: String, value: AnyObject?) { self.name = name originalValue = generators[self.name]?() println("The original value is \(originalValue)") generators[self.name] = { value } } deinit { println("Resetting \(self.name) to \(self.originalValue)") generators[self.name] = { self.originalValue } } } func applyAndResetValue(name: String, value: AnyObject?) { let resetter = ValueResetter(name: name, value: value) println("The value is \(generators[name]?())") } let valueName = "Value" applyAndResetValue(valueName, 1) println("The value is \(generators[valueName]?())") applyAndResetValue(valueName, 2) println("The value is \(generators[valueName]?())")
将输出:
The original value is nil
The value is Optional(1)
Resetting Value to nil
The value is nil
The original value is nil
The value is Optional(2)
Resetting Value to nil
然后在第二次调用deinit时出现EXC_BAD_ACCESS错误。 人们对这次事故的原因有何了解?
答案 0 :(得分:2)
这里可能存在编译错误,但是没有。在对象的deinit中强烈捕获对象。换句话说:
deinit {
println("Resetting \(self.name) to \(self.originalValue)")
generators[self.name] = { self.originalValue }
}
捕获当前正在初始化的self
。
将deinit更改为可以修复崩溃:
deinit {
let value: AnyObject? = self.originalValue
println("Resetting \(self.name) to \(value)")
generators[self.name] = { value }
}