Philip007
Philip007

Reputation: 3230

Objective-C: __block not working

I could not figure out how to change the value of results inside the success block. I use __block like some post suggests but results is forever nil. I set breakpoint inside of block and make sure that JSON is not nil, which download data as I expected.

I am using AFNetworking library if that's relevant.

+(NSArray *)eventsByCityID:(NSString *)cityID startIndex:(NSUInteger)start count:(NSUInteger)count
{
    __block NSArray *results = nil;

    [[DoubanHTTPClient sharedClient] getPath:@"event/list" parameters:@{@"loc":dataSingleton.cityID} success:^(AFHTTPRequestOperation *operation, id JSON) {
        results = [JSON valueForKey:@"events"];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        NSLog(@"download events error: %@ \n\n",error);
    }];

    return results;
}

Upvotes: 0

Views: 319

Answers (1)

bbum
bbum

Reputation: 162712

More likely than not, that [very poorly named] method getPath:parameters:success:failure: is asynchronous.

Thus, you need to tell something in the success block that the value has changed. I.e.

^{
     [something yoManGotEvents:[JSON valueForKey:@"events"]];
 }

(Methods shouldn't be prefixed with get outside of very special circumstances. Third party libraries with lots of API using that prefix outside of said circumstances raise question as to what other system specific patterns they may not be following.)

Upvotes: 3

Related Questions