2010-12-14 3 views
0

NSURLConnection을 사용하여받은 것을 검색하기 위해 검색 창을 만들려고합니다. 지금 내가 무언가를 검색하면 그 문자열은 데이터를 제공하는 비동기 요청이있는 URL로 전송됩니다.NSOperation을 사용하여 검색

NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:urlString] cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:20.0]; 
    [theConnection cancel]; 
    [theConnection release]; 

theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self]; 

은 데이터를 분석하고 성공할 때 알림

-(void)connectionDidFinishLoading:(NSURLConnection *)connection 
    {  
     xmlParser = [[NSXMLParser alloc] data]; 
     [xmlParser setDelegate:xmlGeocoder]; 
     BOOL success = [xmlParser parse]; 

     if(success == YES){ 
      NSLog(@"No Errors"); 

      [[NSNotificationCenter defaultCenter] postNotificationName:@"getArray" object:self]; 

     }else{ 
      NSLog(@"Error Error Error!!!"); 
      [[NSNotificationCenter defaultCenter] postNotificationName:@"failToGetArray" object:self]; 
     } 
} 

을 게시하고 내 searchresultsTableView는 다시로드된다.

self.array1 = [array2 copy]; 
    [self.searchDisplayController.searchResultsTableView reloadData]; 

이러한 모든 방법은 서로 의존하므로 A가 여전히 사용 중이면 B를 실행할 수 없습니다. NSNotificationCenter를 사용하여 해당 코드를 실행하도록 알려줍니다.

하지만 NSOperation을 시험해보고 싶습니다. 어떻게 구현해야할지 모르겠군요. 작업 또는 모든 방법을 사용하여 검색 요청을해야합니까?

누군가이 코드를 어떻게 수행해야하는지 아이디어를 제공 할 수 있습니까? 미리 감사드립니다 ...

답변

2

NSOperation은 매우 유용합니다. 이를 사용하려면 NSOperation을 확장하고 "main"메소드를 오버라이드하십시오. 주 방법에서는 계산/웹 요청 등을 수행합니다. 따라서 NSOperation은 몇 가지 간단한 단계로 래핑 할 수있는 작업에 가장 적합합니다. 모든 단계가 끝나면 모든 것이 좋으며 다음 단계로 계속 진행하거나 작업을 취소합니다. 이 작업이 완료되면 사용자 정의 NSOperation을 인스턴스화하고 NSOperationQueue 객체로 넘겨 주면 스레딩, 시작, 정리 중지 등을 처리 할 수 ​​있습니다.

아래 예제에서 처리 할 프로토콜을 작성했습니다 작업의 완료, 당신이 알림을 사용하는 대신이 접근 방식을 취할 것을 권합니다 - 당신이 즉시 알려야 할 여러 객체가 없다면.

는 NSOperation 클래스를 확장하는 새로운 클래스를 확인하십시오

NSOperation을 확장 객체가 NSOperationQueue의 NSOperation에 "주"방법을 호출하려고 큐 개체에 추가됩니다
//This object takes a "searchTerm" and waits to be "started". 
#import <Foundation/Foundation.h> 

@protocol ISSearchOperationDelegate 

- (void) searchDataReady:(NSArray*) searchResult; 

@end 


@interface ISSearchOperation : NSOperation { 

    id <ISSearchOperationDelegate> delegate; 

    NSString *searchTerm; 
} 

@property(nonatomic, retain) NSString *searchTerm; 

@property(nonatomic, assign) id delegate; 

- (id) initWithSearchTerm:(NSString*) searchString; 

@end 

, 당신이해야합니다 따라서이 방법으로 작업을 마무리하십시오. (없는 경우는 "반환"잘 갔다와 경우 각각 완료 하위 작업 후 내가 테스트하는주의 사항. NSOperation 클래스 그래서 당신은 또한 시험의 경우 반드시, 이 속성은 NSOperationQueue에 의해 설정 될 수의 isCancelled라는 속성이 있습니다 그 메인의 당신의 완료시 설정 한 요약하자면, 당신이 원하는대로 각 단계 간 경우 주요 내부에서 테스트하고 외부에 무언가가 당신의 작업을 취소 한 경우 테스트 그래서) :..

- (id) initWithSearchTerm:(NSString*) searchString { 

    if (self = [super init]) { 

     [self setSearchTerm:searchString]; 
    } 

    return self; 
} 

- (void) main { 

    [self performSelector:@selector(timeOut) withObject:nil afterDelay:4.0]; 
    if ([self isCancelled]) return; 
    NSData *resultData = [self searchWebServiceForString:self.searchTerm]; 
    if (resultData == nil) return; 
    if ([self isCancelled]) return; 
    NSArray *result = [self parseJSONResult:resultData];  
    if ([self isCancelled]) return; 
    if (result == nil) return; 
    [NSObject cancelPreviousPerformRequestsWithTarget:self]; 
    [delegate performSelectorOnMainThread:@selector(searchDataReady:) withObject:result waitUntilDone:YES]; 
} 

// main에서 호출하는 모든 메서드의 구현을 복사하지는 않았지만 다음 서브 작업을 계산할 수있게되기 전에 각 작업을 성공적으로 완료해야하는 "작업"이라는 것을 이해하시기 바랍니다. 그래서 먼저 거기에 타임 아웃 테스트를 넣은 다음 웹 서비스에서 내 데이터를 얻은 다음 구문 분석합니다.

이 모든 것을 얻으려면 대기열이 필요합니다.

어딘가에 큐 설정 :

그래서 수업 시간에 당신은 당신이 할이 조작의 대표가되고 싶어요

NSOperationQueue *q = [[NSOperationQueue alloc] init]; 
[self setQueue:q]; 
[q release]; 


- (void) doSearch:(NSString*) searchString { 

    [queue cancelAllOperations]; 
    ISSearchOperation *searchOperation = [[ISSearchOperation alloc] initWithSearchTerm:searchString]; 
    [searchOperation setDelegate:self]; 
    [queue addOperation:searchOperation]; //this makes the NSOperationQueue call the main method in the NSOperation 
    [searchOperation release]; 
} 

//the delegate method called from inside the NSOperation 
- (void) searchDataReady:(NSArray*) results { 

    //Data is here! 
} 

NSOperations 가진 장점 중 일부는 것입니다을 호출 지점에서 우리는 단순히 객체를 만들고, 델리게이트를 설정하고, 응답을 기다린다. 그러나 언제든지 취소 할 수있는 일련의 스레드 작업이 실행되고 스레드 된 항목이 실패하는 경우 처리 할 수있는 방식으로 처리됩니다.

doSearch 메서드에서 볼 수 있듯이 이전 작업을 취소하여 시작합니다. 사용자가 단어를 입력 할 때마다 웹 서비스를 검색하는 앱에서이 작업을 수행했습니다. 즉, 사용자가 "hello world"를 검색하면 "h", "he", "hel", "hello"등의 검색을 수행하게됩니다. 나는 멈추고 청소하고 싶었습니다.NSOperation은 스레딩의 응답 성을 제공하고 대개는 많은 스레드를 생성하는 혼란이없는 유일한 방법이라는 것을 알게되었습니다. 사용자가 "e"를 입력하자마자 "h"작업을 수행합니다.

희망 사항을 사용하여 시작할 수 있습니다.

관련 문제