Die Antworten, die ich bisher gesehen habe (1, 2, 3) empfehlen GCD die mit dispatch_once
so:Wie führe ich Code einmal und nur einmal in Swift aus?
var token: dispatch_once_t = 0
func test() {
dispatch_once(&token) {
print("This is printed only on the first call to test()")
}
print("This is printed for each call to test()")
}
test()
Ausgang:
This is printed only on the first call to test()
This is printed for each call to test()
Aber warten Sie eine Minute. token
ist eine Variable, so konnte ich dies ganz einfach:
var token: dispatch_once_t = 0
func test() {
dispatch_once(&token) {
print("This is printed only on the first call to test()")
}
print("This is printed for each call to test()")
}
test()
token = 0
test()
Ausgang:
This is printed only on the first call to test()
This is printed for each call to test()
This is printed only on the first call to test()
This is printed for each call to test()
So dispatch_once
ist nichts, wenn wir ich den Wert von token
ändern können! Und token
in eine Konstante zu verwandeln ist nicht einfach, da es vom Typ braucht.
Also sollten wir aufgeben auf dispatch_once
in Swift? Gibt es einen sichereren Weg, Code nur einmal auszuführen?
Objective-C hat das gleiche Problem. Die Idee ist, das "Token" in den gleichen Umfang wie den 'dispatch_once' Block zu stellen (und ihm einen besseren Namen wie' onceToken' zu geben und es RECHTS über den 'dispatch_once' Block selbst zu stellen, so dass es sehr klar ist). – nhgrif
Nun, 'dispatch_once' ist nicht sicherer als eine normale boolesche Variable. – Eric
http://Stackoverflow.com/q/25354882/2792531 – nhgrif