到目前为止,我有这个代码
- (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并完成请求?
答案 0 :(得分: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");
}];
}
}