2013-01-05 6 views
1

현재 3 개의 다른 URL을 직선으로 다운로드하고 비동기식으로 웹 페이지를 다운로드 할 수 있도록 프로그램을 수정하고 싶습니다. 그러나 웹 페이지 다운로드가 프로그램 전에 완료되기를 원합니다 진행됩니다. 온라인에서 튜토리얼을 보았지만 NSOperation 및 NSoperationqueue를 사용할 수 없었습니다. NSOperationQueue 비동기식으로 웹 페이지 다운로드

NSOperation 클래스 I 단순히 웹 페이지

#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 웹 페이지를 동시에하고 이후에 완료

#import <Foundation/Foundation.h> 

@interface LoadPage : NSOperation 

@property (nonatomic, copy) NSURL *URL; 
@property (nonatomic, copy) NSData *webpage; 

- (id)initWithURL:(NSURL*)url; 
- (void)main; 

@end 

을 생성 모두 끝난 나머지 프로그램 실행으로 넘어갑니다.

@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 
} 

나는이에게 프로그램 동결을 실행하면 내가 나쁜 실행 오류가 발생합니다. 내 짐작으로는로드 페이지 끝 부분에 라인을 사용해야합니다.

[MasterParser performSelectorOnMainThread:@selector(parsePage:) 
             withObject:nil 
            waitUntilDone:YES]; 

감사합니다.

+0

어떻게'-parsePage :'가 호출 되었습니까? 프로그램이 정지하면, 그것이 메인 스레드에서 실행되고 있음을 나에게 알린다. 아마 당신이 원하는 것이 아닙니다. 일반적으로이 패턴은 GCD 및 블록을 사용하여 구현하기가 더 쉽습니다. – ipmcc

+0

-pageParse : 버튼 누름에 응답하는 다른 클래스에 의해 호출됩니다. 내가 실제로 발생하는 응용 프로그램에 대해 틀렸어 하나의 스레드 1에 EXC_BAD_ACCESS 예외가 있습니다. GCD를 통해 NSOperation을 선택한 이유는 GCD를 전혀 이해하지 못했던 NSOp 자습서를 다소 이해했기 때문입니다. – user380776

+0

버튼 누름에 대한 응답으로 발생하는 경우 주 스레드에서 발생합니다. NSOperationQueue가 선택의 무기라고 생각되면, 그 중 하나를 만들고 해당 대기열에 -parsePage : off를 호출 한 다음 개별 페이지가 다른 대기열로로드되도록 발송하십시오. – ipmcc

답변

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 

이 질문에 도움을 주신 모든 분들께 다시 한번 감사드립니다.

1

웹 페이지를 다운로드 할 때와 비교하여 구문 분석 자체가 문제가되지 않아야하므로 주 스레드에서 실행하는 경우 지연이 너무 많이 발생해서는 안되지만 별도의 스레드에서 웹 페이지를 구문 분석 할 수 있습니다. 하고 싶다. 제가 지적하고자하는 또 다른 점은 [MasterParser performSelectorOnMainThread:@selector(parsePage:) withObject:nil waitUntilDone:YES];으로 전화를 걸면 이것은 메인 스레드의 +[MasterParser parsePage:nil]입니다. 대신 self (또는 그 객체를 해당 메소드라고 부르는 객체)이어야합니다. [self performSelectorOnMainThread:@selector(parsePage:) withObject:nil waitUntilDone:YES];

+0

'+ [NSData dataWithContentsOfURL :]'은 단지 로컬 파일 이상에서 작동합니다. 질문의 HTTP URL과 확실히 작동합니다. –

+0

@KurtRevis 사과드립니다.대답을 게시하기 전에 몇 가지 조사를 완료해야합니다. – TheAmateurProgrammer

+0

그래, 파싱은 실제로 웹 페이지를 다운로드하는 것이 아니라 스레딩을 사용하고 싶습니다. 그래서 나는 [self performSelectorOnMainThread : @selector (parsePage :) withObject : nil waitUntilDone : YES];를 호출하면 질문이 생깁니다. 이것은 parsePage 메소드를 호출하지만 각 연산은 parsePage를 호출 할 것인가? 모든 작업이 완료되면 parsePage 작업이 계속 진행되어 선형으로 작동하기를 바랍니다. 도와 주셔서 감사합니다. – user380776

관련 문제