Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>According to the <a href="http://developer.apple.com/library/mac/#documentation/Performance/Reference/GCD_libdispatch_Ref/Reference/reference.html#//apple_ref/c/func/dispatch_once" rel="nofollow">apple documentation</a> <code>dispatch_once</code> should not be used in that case!</p> <blockquote> <p>The predicate must point to a variable stored in global or static scope. <strong>The result of using a predicate with automatic or dynamic storage is undefined.</strong></p> </blockquote> <p>An alternative approach would be to use <a href="https://developer.apple.com/library/mac/#documentation/System/Reference/OSAtomic_header_reference/Reference/reference.html" rel="nofollow">atomic operations</a>. That way it can also be ensured that code is only executed once during the lifetime of an object.</p> <pre><code>@implementation MyClass { // int32_t initialized; BOOL initialized; } - (void)myMethod { dispatch_sync(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{ // if (OSAtomicTestAndSetBarrier(1, &amp;initialized) == NO) { if (!initialized) { // do stuff once initialized = YES; } }); }; @end </code></pre> <p>EDIT: <code>initialized</code> has been of type BOOL, which has been corrected thanks to the comments of Chris Devereux and Stephen Canon.</p> <p>EDIT: As Catfish_Man pointed out using atomic operations likely leads to problems. Because of that you would have to wrap the whole stuff with a dispatch_sync or something like that, which then makes using atomic operations pointless.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload