1

我有一个程序,我目前在直线上下载 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];

任何帮助将不胜感激谢谢!

4

2 回答 2

1

与下载网页相比,解析本身应该不是什么大问题,所以如果你在主线程上执行它应该不会造成太大的延迟,但是如果你愿意的话,你可以在单独的线程上解析网页。我想指出的另一件事是,如果您要调用[MasterParser performSelectorOnMainThread:@selector(parsePage:) withObject:nil waitUntilDone:YES];,这将依次调用+[MasterParser parsePage:nil]主线程。相反,它应该是self(或任何对象调用该方法),所以[self performSelectorOnMainThread:@selector(parsePage:) withObject:nil waitUntilDone:YES];

于 2013-01-06T03:36:28.163 回答
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

再次感谢所有帮助回答这个问题的人。

于 2013-01-06T19:26:51.373 回答