我有一个程序,我目前直接下载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];
任何帮助将不胜感激!
答案 0 :(得分:1)
与下载网页相比,解析本身不应该是一个大问题,所以如果你在主线程上执行它不应该创建太多延迟,但如果你愿意,你可以解析单独线程上的网页至。我想指出的另一件事是,如果你要打电话给[MasterParser performSelectorOnMainThread:@selector(parsePage:)
withObject:nil
waitUntilDone:YES];
,这将在主线程上调用+[MasterParser parsePage:nil]
。相反它应该是self
(或任何对象调用该方法),所以[self performSelectorOnMainThread:@selector(parsePage:)
withObject:nil
waitUntilDone:YES];
答案 1 :(得分:0)
首先,我要感谢所有帮助我回答这个问题的人。关键是添加行
self=[super init];
to the initWithURL method after that everything started working.
#import "LoadPage.h"
@implementation LoadPage
@synthesize URL;
@synthesize webpage;
- (id)initWithURL:(NSURL*)url{
self = [super init];
[self setURL:url];
return self;
}
- (void)main {
NSData *page = [NSData dataWithContentsOfURL:URL];
[self setWebpage:page];
}
@end
再次感谢所有帮助回答此问题的人。