我有一个程序,目前可以直线下载 3 个不同的 URL,我想对其进行修改,以便可以异步下载网页,但我希望在程序进行之前完成所有 3 个网页下载。我已经在网上看到了教程,但我仍然无法让 NSOperation 和 NSoperationqueue 工作。
这是我创建的 NSOperation 类
#import <Foundation/Foundation.h>
@interface LoadPage : NSOperation
@property (nonatomic, copy) NSURL *URL;
@property (nonatomic, copy) NSData *webpage;
- (id)initWithURL:(NSURL*)url;
- (void)main;
@end
它只是为了下载网页而设计的
#import "LoadPage.h"
//Loadpage.m
@implementation LoadPage
@synthesize URL;
@synthesize webpage;
- (id)initWithURL:(NSURL*)url{
[self setURL:url];
return self;
}
//Download Webpage function
- (void)main {
NSData *page = [NSData dataWithContentsOfURL:URL];
[self setWebpage:page];
}
我想下载 3 个单独的网页,并同时完成所有这 3 个网页,并在它们全部完成后继续执行程序的其余部分。
@interface MasterParser : NSObject{
NSOperationQueue *queue;
}
-(NSMutableArray *)loadPlayer:(NSString *)name;
@end
@implementation MasterParser
-(NSMutableArray *)parsePage:(NSString *)name{
NSURL *google = [NSURL URLWithString:@"http://www.Google.com"];
NSURL *yahoo = [NSURL URLWithString:@"http://www.yahoo.com"];
NSURL *mlbtraderumors = [NSURL URLWithString:@"http://www.mlbtraderumors.com"];
LoadPage *gpage = [[LoadPage alloc] initWithURL:google];
LoadPage *ypage = [[LoadPage alloc] initWithURL:yahoo];
LoadPage *mpage = [[LoadPage alloc] initWithURL:mlbtraderumors];
queue = [[NSOperationQueue alloc] init];
[queue addOperation:gpage];
[queue addOperation:ypage];
[queue addOperation:mpage];
[queue waitUnitilAllOperationsAreFinished];
NSData *webpage = [gpage webpage];
//...etc do all the operations and parsing with the webpages after all the downloads are done
}
当我运行此程序时,程序卡住并且出现严重的执行错误。我怀疑我需要在 loadpage.m 末尾使用一行
[MasterParser performSelectorOnMainThread:@selector(parsePage:)
withObject:nil
waitUntilDone:YES];
如有任何帮助,我们将不胜感激!
最佳答案
与下载网页相比,解析本身不应该是一个太大的问题,因此如果您在主线程上执行它,它不会产生太多的延迟,但如果您愿意,您可以在单独的线程上解析网页到。我想指出的另一件事是,如果您要调用 [MasterParser PerformSelectorOnMainThread:@selector(parsePage:)
withObject:nil
waitUntilDone:YES];
,这将依次在主线程上调用+[MasterParser parsePage:nil]
。相反,它应该是 self (或调用该方法的任何对象),因此 [self PerformSelectorOnMainThread:@selector(parsePage:)
withObject:nil
waitUntilDone:YES];
关于objective-c - NSOperationQueue 异步下载网页,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14176534/