Xcode8 Beta EXC_BAD_ACCESS创建弱引用时出现错误

时间:2016-07-14 13:04:56

标签: swift exc-bad-access weak-references xcode8

以下代码是从Weak References section of the Official document

复制而来的
class Person {
    let name: String
    init(name: String) { self.name = name }
    var apartment: Apartment?
    deinit { print("\(name) is being deinitialized") }
}

class Apartment {
    let unit: String
    init(unit: String) { self.unit = unit }
    weak var tenant: Person?
    deinit { print("Apartment \(unit) is being deinitialized") }
}

var john: Person?
var unit4A: Apartment?

john = Person(name: "John Appleseed")
unit4A = Apartment(unit: "4A")

john!.apartment = unit4A
unit4A!.tenant = john //Error!

它基本上描述了person类型实例和Apartment类型实例之间的强弱参考关系(请参见下图)

enter image description here

然而,当我运行代码时,我收到了一个错误。

问题:我该如何解决?

enter image description here

AlessandroOrrù先生的回复,(我再次复制粘贴,但仍然给我错误)

enter image description here

1 个答案:

答案 0 :(得分:1)

这现在可以正常工作 - 该错误已在XCode 8 GM Seed中修复。

原始答案:

它是XCode8 beta 3游乐场中的一个错误。我复制了你的代码,尝试了Apple的例子,并尝试将其减少到最低限度:

class A { var b:B? }

class B { weak var a:A? }

let b = B()
let a = A()

a.b=b
b.a=a

所有工作都按预期使用XCode 7.3.1和Swift 2.2。所有都失败了XCode 8 beta 3和Swift 3.错误是:

error: Playground execution aborted: error: Execution was interrupted, reason: EXC_BAD_ACCESS (code=EXC_I386_GPFLT).

它只在游乐场 - 它在应用程序中很好。 (我尝试过Mac OS命令行程序)