0

これまでにこのコードを持っているねえ


- (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を返すにはどうすればよいですか?

4

1 に答える 1

1

次のようにします。

- (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");
        }];
    }
}
于 2012-03-17T17:42:15.040 に答える