この回答を2日間検索した後、解決策が見つかりました。
- イメージを非同期でダウンロードするには、GCD を使用します。
- 画像をメモリに保存するには、NSMutableDictionary を使用します。
ここで Duncan C が説明した解決策を見つけました。
実装方法:
- (void)viewDidLoad
{
(...)
dispatch_queue_t mainQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
imagesDictionary = [[NSMutableDictionary alloc] init];
(...)
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
(...)
NSData *imageData = [imagesDictionary objectForKey:@"IMAGE URL"];
if (imageData)
{
UIImage* image = [[UIImage alloc] initWithData:imageData];
imageFlag.image = image;
NSLog(@" Reatriving ImageData...: %@", @"IMAGE URL");
}
else
{
dispatch_async(mainQueue, ^(void) {
NSString *url = @"IMAGE URL";
NSData *imageData = [[NSData alloc] initWithContentsOfURL:[NSURL URLWithString:url]];
UIImage* image = [[UIImage alloc] initWithData:imageData];
imageFlag.image = image;
[imagesDictionary setObject:imageData forKey:@"IMAGE URL"];
NSLog(@" Downloading Image...: %@", @"IMAGE URL");
});
}
(...)
}
GitHub のプロジェクト: https://github.com/GabrielMassana/AsynchronousV2.git
プロジェクトが大きく、セルが多い場合、メモリが不足する可能性があることを知っています。しかし、この解決策は初心者にとっては良いアプローチだと思います。
プロジェクトについてどう思いますか?プロジェクトが非常に大きい場合、最適なオプションはイメージをディスクに保存することですか? しかし、問題は、ディスクのメモリが不足する可能性があることですよね? おそらく、ディスクからすべてのイメージを削除するメカニズムが必要です。