Reputation: 133
Hey im having this code so far
- (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;
}
my problem is return self is called before the async request is finished, how do i return self with the request finished without a synchronous request?
Upvotes: 0
Views: 193
Reputation: 62686
do it like this:
- (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");
}];
}
}
Upvotes: 1