简体   繁体   中英

the value of __block variable is not changed

The code below will load the value of the asset asynchronously. I wait for it using while loop.

    AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:aAudioLink options: nil];
    [asset loadValuesAsynchronouslyForKeys:keys 
                 completionHandler:^{                                           
                canExit = TRUE;
                         }];

    while (canExit == FALSE) {
        // NSLog (@"canExist = FALSE");     
    }

    NSLog(@"canExist = TRUE");

If NSLog statement is commented like the code above, the last NSLog will not be called. If NSLog statement is NOT commented, the last NSLog is called.

The block and the code outside the block run on different threads and both of which are not main thread.

What is the reason for that?

I think you shouldnt be using a while loop for this. Recently i was dealing with an application in which i had to make use of AVAsset to generate thumbnail image for the asset.i ended up using a dispatch semaphore for blocking the thread until the image was generated asynchronously.

Why cant you try the following.

 dispatch_semaphore_t sema = dispatch_semaphore_create(0);
 dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT,0);

 AVURLAsset *asset = [[AVURLAsset alloc] initWithURL:aAudioLink options: nil];

dispatch_async(queue, ^{

[asset loadValuesAsynchronouslyForKeys:keys 
             completionHandler:^{                                           
            canExit = TRUE;
            dispatch_semaphore_signal(sema);
             }];
    });



dispatch_semaphore_wait(sema, DISPATCH_TIME_FOREVER);
dispatch_release(sema);

It should work if I'm right.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM