我通过 RSS 提要获取数据并在表格视图单元格中显示每篇文章。每个单元格都有一个图像视图,设置为默认图像。如果页面有图像,则图像将替换为文章中的图像。截至目前,每个单元格都从网页下载源代码,导致应用程序在我推送视图控制器和尝试滚动时出现延迟。
这是我在cellForRowAtIndexPath:
方法中所拥有的。
NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"link"];
storyLink = [storyLink stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *sourceCode = [NSString stringWithContentsOfURL:[NSURL URLWithString:storyLink] encoding:NSUTF8StringEncoding error:&error];
NSString *startPt = @"instant-gallery";
NSString *startPt2 = @"<img src=\"";
if ([sourceCode rangeOfString:startPt].length != 0) { //webpage has images
// find the first "<img src=...>" tag starting from "instant-gallery"
NSString *trimmedSource = [sourceCode substringFromIndex:NSMaxRange([sourceCode rangeOfString:startPt])];
trimmedSource = [trimmedSource substringFromIndex:NSMaxRange([trimmedSource rangeOfString:startPt2])];
trimmedSource = [trimmedSource substringToIndex:[trimmedSource rangeOfString:@"\""].location];
NSURL *url = [NSURL URLWithString:trimmedSource];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
cell.picture.image = image;
有人建议使用NSOperationQueue
. 这种方式会是一个很好的解决方案吗?
编辑:
dispatch_queue_t someQueue = dispatch_queue_create("cell background queue", NULL);
dispatch_async(someQueue, ^(void){
NSError *error = nil;
NSString * storyLink = [[stories objectAtIndex: storyIndex] objectForKey: @"link"];
storyLink = [storyLink stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
NSString *sourceCode = [NSString stringWithContentsOfURL:[NSURL URLWithString:storyLink] encoding:NSUTF8StringEncoding error:&error];
NSString *startPt = @"instant-gallery";
NSString *startPt2 = @"<img src=\"";
if ([sourceCode rangeOfString:startPt].length != 0) { //webpage has images
// find the first "<img src=...>" tag starting from "instant-gallery"
NSString *trimmedSource = [sourceCode substringFromIndex:NSMaxRange([sourceCode rangeOfString:startPt])];
trimmedSource = [trimmedSource substringFromIndex:NSMaxRange([trimmedSource rangeOfString:startPt2])];
trimmedSource = [trimmedSource substringToIndex:[trimmedSource rangeOfString:@"\""].location];
NSURL *url = [NSURL URLWithString:trimmedSource];
NSData *data = [NSData dataWithContentsOfURL:url];
UIImage *image = [UIImage imageWithData:data];
dispatch_async(dispatch_get_main_queue(), ^(void){
cell.picture.image = image;
});
});
dispatch_release(someQueue);
return cell;
}