objective c - dipatch_async releases local variable -


i did not find suitable answers on web, post question here.

__block int test = 1; dispatch_async(dispatch_get_main_queue(), ^{     test = 2; }); nslog(@"%i",test); 

this code result in console message "1".

__block nsstring *test = @"no"; dispatch_async(dispatch_get_main_queue(), ^{     test = @"yes"; }); nslog(@"%@",test); 

this code result in console message "no".

why so? thought __block identifier should solve problems in case. hypothesis local variable copied , code inside block hadn't modify outside itself.

how can modify local variables inside dispatch_async?

sorry if noob question.

you dispatching asynchronously main queue.

the dispatch_async returns before block executed (coincidentally).

to underscore how non-deterministic concurrent programming can be:

note nslog() might see new value maybe once in blue moon. might not ever see in debugging environment, customer might encounter behavior 3 years on system configuration doesn't exist today.

to fix?

dispatch_sync() thereby ensuring background queue , main queue acting less efficient single serial queue.

... or ...

use kind of synchronization construct message main queue local queue when operation done. i.e.:

dispatch_async(otherqueue, ^{      ... ...;      dispatch_async(firstqueue, ^{           done(calculatedvalue);      }; }; 

Comments

Popular posts from this blog

SPSS keyboard combination alters encoding -

Add new record to the table by click on the button in Microsoft Access -

javascript - jQuery .height() return 0 when visible but non-0 when hidden -