我的函数中有一段这样的代码。我做了一个循环,在按钮内创建一个异步图像。但是当我运行它时,我的按钮不显示异步图像。请告诉我我的代码有什么问题。当我打印 NSLog url 时,它运行良好并显示所有图像 url。
// ADD BUTTON
UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
[btn setFrame:CGRectMake(topLeft.x,topLeft.y,width,height)];
//Asyncronous Image
NSMutableString *imageUrl;
if ([[[type objectAtIndex:btnNumber] objectForKey:@"LAST_CONTENT_IMAGE"] isEqualToString:@""] || [[type objectAtIndex:btnNumber] objectForKey:@"LAST_CONTENT_IMAGE"] == nil) {
imageUrl = [NSMutableString stringWithFormat:@"bank_images/actual/"];
}else{
imageUrl = [[type objectAtIndex:btnNumber] objectForKey:@"LAST_CONTENT_IMAGE"];
}
NSURL *url1 = [NSURL URLWithString:imageUrl];
NSLog(@"URL GBR : %@", url1);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *stringSub = [imageUrl substringWithRange:NSMakeRange (imageUrl.length-9, 9)];
NSString *path = [NSString stringWithFormat:@"%@/%u_%@", documentsDirectory,[GlobalVariable sharedInstance].indexCategoryGlobal,stringSub];
if ([[NSFileManager defaultManager] fileExistsAtPath:path])
{
NSData *img = [NSData dataWithContentsOfFile:path];
UIImage *imageExist = [UIImage imageWithData:img];
image = imageExist;
[btn setImage:image forState:UIControlStateNormal];
}else{
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0);
dispatch_async(queue, ^{
//This is what you will load lazily
NSData *data1 = [NSData dataWithContentsOfURL:url1];
dispatch_sync(dispatch_get_main_queue(), ^{
image = [UIImage imageWithData:data1];
[btn setImage:image forState:UIControlStateNormal];
if ([stringSub isEqualToString:@"s/actual/"]){
image = [UIImage imageNamed:@"default_thumb.png"];
[btn setImage:image forState:UIControlStateNormal];
}
[[NSFileManager defaultManager] createFileAtPath:path
contents:data
attributes:nil];
});
});
}
[btn setTag:btnNumber];