Created
February 1, 2018 10:27
-
-
Save matkuznik/cfb85d291b13909ac696942982c9ffeb to your computer and use it in GitHub Desktop.
This file contains 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 DoTaskClass { | |
let identifier: String | |
init(identifier: String) { | |
self.identifier = identifier | |
} | |
func getTask() -> (() -> ()) { | |
return { [weak self] in | |
withUnsafePointer(to: &self) { | |
print("Optional self \(self) has address: \($0)") | |
} | |
if var this = self { | |
print("DoTaskClass::getTask identifier \(this.identifier)") | |
withUnsafePointer(to: &this) { | |
print("Optional self \(this) has address: \($0)") | |
} | |
} | |
print("\n") | |
} | |
} | |
deinit { | |
print(" \(identifier) ☠️ \n") | |
} | |
} | |
do { | |
print("_______________ Case 1 _______________") | |
func replace(_ p: UnsafeMutablePointer<DoTaskClass>) { | |
var pointer = p | |
// print("before \(pointer.pointee.identifier)") //This will couse a crash EXC_BAD_ACCESS if pointer.pointee is nil | |
pointer.pointee = DoTaskClass(identifier: "---2---") | |
print("after \(pointer.pointee.identifier)\n") | |
} | |
var taskHolder: DoTaskClass? = DoTaskClass(identifier: "___1___") | |
let task = taskHolder!.getTask() | |
task() | |
var pointer = UnsafeMutablePointer(&taskHolder!) | |
taskHolder = nil | |
task() | |
replace(pointer) | |
task() | |
} | |
do { | |
print("_______________ Case 2 _______________") | |
func replace(_ p: UnsafeMutablePointer<DoTaskClass>) { | |
var pointer = p | |
// print("before \(pointer.pointee.identifier)") //This will couse a crash EXC_BAD_ACCESS if pointer.pointee is nil | |
pointer.pointee = DoTaskClass(identifier: "---2---") | |
print("after \(pointer.pointee.identifier)\n") | |
} | |
var taskHolder: DoTaskClass? = DoTaskClass(identifier: "___1___") | |
let task = taskHolder!.getTask() | |
task() | |
var pointer = UnsafeMutablePointer(&taskHolder!) | |
replace(pointer) | |
task() | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment