我有一个SSCollectionView,它是在NSCollectionView和UITableView之后建模的。它调用一个函数来在indexPath上加载每个项目。
我想异步地将图像加载到每个路径中。
- (SSCollectionViewItem *)collectionView:(SSCollectionView *)aCollectionView itemForIndexPath:(NSIndexPath *)indexPath {
....
[self startLoadingItem:item indexPath:indexPath];
return item;
}
-(void)startLoadingItem:(SSCollectionViewItem *)collectionViewItem indexPath:(NSIndexPath *)indexPath
{
[SEThreadInvocation detachNewThreadSelector:@selector(loadItem:indexPath:) toTarget:self withObjects:collectionViewItem,indexPath, nil];
}
SEThreadInvocation只是NSThread的子类,因此我可以向选择器发送多个对象。
-(void)loadItem:(SSCollectionViewItem *)collectionViewItem indexPath:(NSIndexPath *)indexPath {
...
collectionViewItem.imageView.image = imageToDisplay;
}
发生的事情是代码最初有效,但每次集合重新加载(通常)时,它会将图像随机地放在集合视图中。
我相信这是因为我的SSCollectionViewItem每次都指向不同的内存位置而且我的项目不是线程安全的,因此它只是在内存发生变化时将图像标记在各处。
另外,我认为它可能正在替换内存中的图像,因此我将其替换为数字,并且在重新加载时数字会在整个集合视图中反弹。
如何在这种情况下使我的对象线程安全?
答案 0 :(得分:1)
SSToolkit有一个示例Catalog项目,它有一个SSCollectionView演示。它以您需要的方式加载图像。