dimanche 4 janvier 2015

Capturing self in the block temporarily


Vote count:

0




Having a runtime error when program is compiled, purposefully the instantiation of SomeObject is short lived but the block getting passed captures the reference, doesn't work in playground but shows the error when the program is compiled and run.


Objective is to hold the reference temporarily of short lived objects SomeObject until callback gets completed.



import Foundation

class SomeObject {

func go() {
anotherObject.asyncCall({ [unowned self] in
self.complete()
})
}

func complete() {
println("received callback after 5 sec")
}
}

class AnotherObject {

var callback: (() -> ())?

init() {}

func asyncCall(callback: () -> ()) {
self.callback = callback

let delay = 5 * Double(NSEC_PER_SEC)
let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay))

dispatch_after(time, dispatch_get_main_queue(), { [unowned self] in
self.callback!()
})
}
}

var anotherObject = AnotherObject() //not global object but permanent lived

for i in 1...3 {
var instance = SomeObject() //short lived objects
instance.go()
}


asked 1 min ago







Capturing self in the block temporarily

Aucun commentaire:

Enregistrer un commentaire