Last active
October 23, 2015 23:48
-
-
Save eonil/be61e623069f57d912e9 to your computer and use it in GitHub Desktop.
Swfit weak reference undefined behaviour case. (Swift 2.0)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class AAA { | |
deinit { | |
print("AAA deinit") | |
callbackOnDeinit!(self) | |
} | |
var callbackOnDeinit: (AAA->())? | |
} | |
class BBB { | |
weak var aaa: AAA? { | |
didSet { | |
aaa!.callbackOnDeinit = { [weak self] in | |
print("self.aaa when it deinit: \(self!.aaa)") | |
print("$0 when it deinit: \($0)") | |
self!.strongRefAfterDeinit = $0 | |
} | |
} | |
} | |
var strongRefAfterDeinit: AAA? | |
} | |
var aaa = AAA() as AAA? | |
let bbb = BBB() | |
bbb.aaa = aaa | |
aaa = nil | |
print("now aaa = \(aaa)") | |
print("bbb.aaa = \(bbb.aaa)") | |
/// Result of this line is undefined. It crashes, or even *works*. | |
print("bbb.strongRefAfterDeinit = \(bbb.strongRefAfterDeinit)") | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AAA deinit | |
self.aaa when it deinit: nil | |
$0 when it deinit: CommonModelArchTest.AAA | |
now aaa = nil | |
bbb.aaa = nil | |
(program crashes here) |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
AAA deinit | |
self.aaa when it deinit: nil | |
$0 when it deinit: CommonModelArchTest.AAA | |
now aaa = nil | |
bbb.aaa = nil | |
bbb.strongRefAfterDeinit = Optional(CommonModelArchTest.AAA) | |
Program ended with exit code: 0 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment