Wie führe ich code nur einmal in Swift?

Die Antworten, die ich bisher gesehen habe (Eins, Zwei, Drei) empfehlen die Verwendung von GCD ' s dispatch_once so:

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()

Ausgabe:

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()

Ausgabe:

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 von keinerlei nutzen, wenn wir ich kann, ändern Sie den Wert von token! Und drehen token in eine Konstante ist nicht einfach, da muss der Typ UnsafeMutablePointer<dispatch_once_t>.

Sollen wir also aufgeben dispatch_once im Swift? Gibt es eine sicherere Möglichkeit zum ausführen von code nur einmal?

Objective-C hat das gleiche problem. Die Idee ist, die token im gleichen Bereich wie die dispatch_once block, und geben Sie ihm einen besseren Namen wie onceToken und legen Sie es RECHTS oben die dispatch_once block selbst, so dass es sehr klar).
na dann dispatch_once ist nicht sicherer als mit einem normalen boolean-variable.
stackoverflow.com/q/25354882/2792531
Eric, eine Frage über die Verwendung eines gewöhnlichen bool versus dispatch_once wäre wahrscheinlich ein sehr besser, die Diskussion für Stack-Überlauf. Ich würde ganz gerne sehen, dass die Antwort (wenn es nicht schon gefragt worden, & hier beantwortet).
Der neueste Antworten (wie in deinen Referenzen #1 und #3) führen Sie nicht empfehlen GCD aber eine statische Klasseneigenschaft (die ist faul initialisiert werden, die in einer thread-sicheren Art und Weise).

InformationsquelleAutor Eric | 2015-12-10

Schreibe einen Kommentar