سؤال

I really don't understand how to handle asynchronous requests.

I have this method

- (NSString *)getUserID:(void(^)(NSString *result))handler {
    __block NSMutableString *returner = [[NSMutableString alloc] init];
    [TClient downloadUserID:^(NSString *getIt){
        //NSLog(getIt);
        returner = [NSMutableString stringWithFormat:@"%@", getIt];
        handler(returner);
    }];
    return @"getIt, or what I just handled - returner";
}

and I want to return getIt. How? Where? Why isn't it letting me just do it?

هل كانت مفيدة؟

المحلول

Modify the method:

- (void)getUserID:(void(^)(NSString *result))handler {
    [TClient downloadUserID:^(NSString *getIt){
        if(handler) {
            handler(getIt);
        }
    }];
}

Since there's an asynchronous network request, the method can not return the result. You should handle result at handler's block.

[self getUserID:^(NSString *result) {
    NSLog(@"%@", result); // log user's ID
    someObject.userID = result; // and pass it to the other object
}];
مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top