2013-05-07 68 views
1

我试图保存在UITableViewControllercellForRowInIndexPath方法中异步检索的图像数组。在cellForRowInIndexPath中创建数组

不幸的是,该数组没有完全填充或以不正确的顺序排列。

代码我tableview:cellForRowAtIndexPath方法内的是:

// populate the cell's image 
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); 

dispatch_async(queue, ^{ 
    NSURL *url = [NSURL URLWithString:[newsModel url]]; 
    NSData *data = [NSData dataWithContentsOfURL:url]; 
    img = [[UIImage alloc] initWithData:data] ; 
    [imageArray insertObject:img atIndex:[indexPath row]]; 

    dispatch_sync(dispatch_get_main_queue(), ^{ 
     // make image standard size 
     CGSize imageSize = CGSizeMake(40, 40); 
     UIGraphicsBeginImageContext(imageSize); 
     CGRect imageRect = CGRectMake(0.0, 0.0, imageSize.width, imageSize.height); 
     [img drawInRect:imageRect]; 

     cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext(); 
     UIGraphicsEndImageContext(); 

     [cell setNeedsLayout]; 
    }); 
}); 

两者imageArray(NSMutableArray)和IMG(UIImage)是__bool类型。

在此先感谢您的帮助。

回答

2

尝试存储与阵列的关键就地字典,因为没有机会复制后插入使用字典

AllValue对于前阵:

imageArray =[[dict allValues]mutableCopy]; 
NSMutableDictionary *dict=[[NSMutableDictionary alloc]init]; 
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0); 

dispatch_async(queue, ^{ 
NSURL *url = [NSURL URLWithString:[newsModel url]]; 
NSData *data = [NSData dataWithContentsOfURL:url]; 
img = [[UIImage alloc] initWithData:data] ; 

[dict setObject:img forKey:indexPath.row] 
dispatch_sync(dispatch_get_main_queue(), ^{ 
// make image standard size 
CGSize imageSize = CGSizeMake(40, 40); 
UIGraphicsBeginImageContext(imageSize); 
CGRect imageRect = CGRectMake(0.0, 0.0, imageSize.width, imageSize.height); 
[img drawInRect:imageRect]; 

cell.imageView.image = UIGraphicsGetImageFromCurrentImageContext(); 
UIGraphicsEndImageContext(); 
[cell setNeedsLayout]; 
}); 
}); 
imageArray =[[dict allValues]mutableCopy]; 
+0

工程。只需将键设置为对象即可。非常感谢! – Jack 2013-05-07 12:52:30

0

下载完成后不要尝试修改单元格,您不知道它是否被重用。只需保存图像,然后询问表格视图reloadData(确保您要求重新加载主线程)。