2013-05-07 71 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(確保您要求重新加載主線程)。