我有一个程序,我目前在直线上下载 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];
任何帮助将不胜感激谢谢!