簡體   English   中英

在UITableView中緩存圖像

[英]Caching images in UITableView

我正在將圖片加載到與單元格文本相對應的表格視圖中,因此每個圖像都是不同的。 當用戶向下滾動時,iOS必須手動從SSD重新加載每個圖像,因此滾動非常不穩定。 如何緩存圖像或防止需要重新創建表視圖單元? 其他人則通過使用imageNamed:解決了他們的問題,因為iOS將自動緩存您的圖像,但是我是從文檔目錄而不是應用程序捆綁包加載圖像。 我該怎么辦? 謝謝。

- (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.
    return [issues count];

}

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {

        cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:CellIdentifier] autorelease];

    }


    // Set up the cell...
    NSDictionary *dic = [self.issues objectAtIndex:indexPath.row];

    cell.text = [dic objectForKey:@"Date"];

    cell.imageView.image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/issues/%@/cover.png", documentsDirectory, [dic objectForKey:@"Directory Name"]]];

    return cell;

}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {

        return 150;

}

字典的排列就是您的模型,因此這將是很自然的地方。 棘手的部分是使模型可變。 您可以在模型中使模型可變,也可以在緩存圖像時跳過模型。 我建議使用前者,但在此處進行編碼以匹配您現有的代碼...

- (UIImage *)imageForIndexPath:(NSIndexPath *)indexPath {

    NSDictionary *dic = [self.issues objectAtIndex:indexPath.row];
    UIImage *image = [dic valueForKey:@"cached_image"];

    if (!image) {
        image = [UIImage imageWithContentsOfFile:[NSString stringWithFormat:@"%@/issues/%@/cover.png", documentsDirectory, [dic objectForKey:@"Directory Name"]]];
        NSMutableDictionary *updatedDictionary = [NSMutableDictionary dictionaryWithDictionary:dic];
        [updatedDictionary setValue:image forKey:@"cached_image"];
        NSMutableArray *updatedIssues = [NSMutableArray arrayWithArray:self.issues];
        [updatedIssues replaceObjectAtIndex:indexPath.row withObject:[NSDictionary dictionaryWithDictionary:updatedDictionary]];
        self.issues = [NSArray arrayWithArray:updatedIssues];
    }
    return image;
}

在列表中的第一個滾動中這會變得不穩定,此后會更加平滑。 如果您不希望初次嘗試,並且在視圖出現之前引起一點延遲,則可以提前遍歷模型並強制加載:

for (int i=0; i<self.issues.count; i++) {
    NSIndexPath *indexPath = [NSIndexPath indexPathForRow:i inSection:0];
    (void)[self imageForIndexPath:indexPath];
}

最后一件事-另一個解決方案是可變數組,以匹配問題數組。 可能還不錯,但我常常為我的模型包括一些緩存的計算而感到高興。 如果您發現自己在其他地方使用了問題數組,那么您會很高興所有圖像都得到了照顧。

除了緩存外,您還可以考慮使用Grand Central Dispatch在后台加載圖像。 加載單元格后,放入UIActivityIndi​​cator,然后在單獨的線程中將其替換為圖像。

還要檢查有關圖像卡頓的相關答案: iOS中的非延遲圖像加載

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM