johan
johan

Reputation: 6656

Passing value types between block

From what I've understood it's possible to make an object available between blocks (and queues?) by using the __block modifier.

-(void)performRequest: (void (^)(NSArray* outcome))completion
 {
    dispatch_async(dispatch_get_global_queue(0,0), ^{
                // do some request

            __block NSArray * result = [[NSArray alloc]init]; //Outcome of the request.

            completion(result);
        });
}

Let's assume that the completion block will dispatch_async on the main thread

I suppose it should be possible to do this with value types without the __block identifier. Im I right?

-(void)performRequest: (void (^)(int outcome))completion
{
    dispatch_async(dispatch_get_global_queue(0,0), ^{
            // do some request

        int result = 10; //Outcome of the request.

        completion(result);
    });
}

Upvotes: 0

Views: 76

Answers (1)

Lily Ballard
Lily Ballard

Reputation: 185671

The use of __block in your first code snippet is completely pointless.

The entire purpose of __block is to make the value remain mutable when captured in another block. You're not capturing result anywhere.

Note that under MRR, __block has the side-effect of preventing the capturing block from retaining the value, making it an oft-used way to break a retain cycle. Under ARC, this isn't true. If you need to avoid a retain cycle then you need to use an __unsafe_unretained or __weak value. That said, again, none of this applies to your presented code snippet.

Upvotes: 2

Related Questions