相关疑难解决方法(0)

从UITableView单元格中的URL加载异步图像 - 滚动时图像更改为错误的图像

我写了两种方法来在我的UITableView单元格内异步加载图片.在这两种情况下,图像都会正常加载,但是当我滚动表格时,图像会改变几次,直到滚动结束并且图像将返回到右图像.我不知道为什么会这样.

#define kBgQueue dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0)

- (void)viewDidLoad
{
    [super viewDidLoad];
    dispatch_async(kBgQueue, ^{
        NSData* data = [NSData dataWithContentsOfURL: [NSURL URLWithString:
                                                       @"http://myurl.com/getMovies.php"]];
        [self performSelectorOnMainThread:@selector(fetchedData:)
                               withObject:data waitUntilDone:YES];
    });
}

-(void)fetchedData:(NSData *)data
{
    NSError* error;
    myJson = [NSJSONSerialization
              JSONObjectWithData:data
              options:kNilOptions
              error:&error];
    [_myTableView reloadData];
}    

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    // Return the number of sections.
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    // Return the number of rows in the section.
    // Usually the number of items in your array (the one that holds your …
Run Code Online (Sandbox Code Playgroud)

cocoa-touch objective-c uitableview ios

151
推荐指数
5
解决办法
13万
查看次数

DispatchQueue.main.async 阻塞主线程

我一直在尝试在 Swift 3.0 中创建一个照片库,我想将存储在文档目录中的图像异步加载到集合视图中。我尝试过DispatchQueue.main.async,但它会阻塞主线程并使应用程序冻结几秒钟:

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let identifier = "ImageCell"
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: identifier, for: indexPath) as! ImageCell
    let url = self.imageURL[indexPath.row]
    cell.lazyLoadImage(from: url)
    return cell
}
Run Code Online (Sandbox Code Playgroud)

和 ImageCell 类:

class ImageCell: UICollectionViewCell {
    @IBOutlet weak var imageView: UIImageView!

    func lazyLoadImage(from url: URL) {
        DispatchQueue.main.async {
            if let image = UIImage(contentsOfFile: url.path) {
                self.imageView.image = image
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

我感谢您的帮助。谢谢。

ios uicollectionview swift

2
推荐指数
1
解决办法
3536
查看次数