вернуть себя до завершения асинхронного запроса - PullRequest
0 голосов
/ 17 марта 2012

Эй, у меня есть этот код до сих пор


- (id)initWithDictionary:(NSDictionary *)aDictionary {
    self = [super init];
    if (!self) {
        return nil;
    }

    _userAvatar = [self getUserAvatar:[aDictionary objectForKey:@"user_avatar"]];
    _userId = [aDictionary objectForKey:@"user_id"];
    _username = [aDictionary objectForKey:@"username"];
    _userEmail = [aDictionary objectForKey:@"user_email"];
    return self;
}


- (UIImage *)getUserAvatar:(NSString *)avatarPath {

    __block UIImage *avatarImage = [[UIImage alloc]init];
    if ([avatarPath length] != 0) {
        [[AFFnBAPIClient sharedClient] setDefaultHeader:@"Accept" value:@"image/png"];
        [[AFFnBAPIClient sharedClient] getPath:FNB_DOWNLOAD_PATH parameters:[NSDictionary dictionaryWithObject:avatarPath forKey:@"avatar"] success:^(AFHTTPRequestOperation *operation, id image) {
            avatarImage = image;
        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error");
        }];
    } else {
        UIImage *placeholderImage = [UIImage imageNamed:@"placeholder.png"];
        avatarImage = placeholderImage;
    }
    return avatarImage;
}

моя проблема в том, что return self вызывается до завершения асинхронного запроса, как мне вернуть self с завершенным запросом без синхронного запроса?

1 Ответ

1 голос
/ 17 марта 2012

сделай так:

- (id)initWithDictionary:(NSDictionary *)aDictionary {
    self = [super init];
    if (self) {

        // for starters, it's a placeholder
        self.userAvatar = [UIImage imageNamed:@"placeholder.png"];

        // now go get the avatar, fill it in whenever the get finishes.
        // notice there's no return value.
        [self getUserAvatar:[aDictionary objectForKey:@"user_avatar"]];

        // make sure these are retained (or strong in ARC) properties.
        // your code looked like it was releasing these
        self.userId = [aDictionary objectForKey:@"user_id"];
        self.username = [aDictionary objectForKey:@"username"];
        self.userEmail = [aDictionary objectForKey:@"user_email"];
    }
    return self;
}

// see - no return value.  it's asynch
- (void)getUserAvatar:(NSString *)avatarPath {

    // don't need a __block var here
    if ([avatarPath length] != 0) {
        [[AFFnBAPIClient sharedClient] setDefaultHeader:@"Accept" value:@"image/png"];
        [[AFFnBAPIClient sharedClient] getPath:FNB_DOWNLOAD_PATH parameters:[NSDictionary dictionaryWithObject:avatarPath forKey:@"avatar"] success:^(AFHTTPRequestOperation *operation, id image) {

            // self got a retain+1 while this was running.
            self.userAvatar = image;

        } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
            NSLog(@"Error");
        }];
    }
}
...