2012-11-22 4 views
1

내 응용 프로그램은 여기에서와 같이 네트워크 연결을 사용하고 있습니다 :네트워크 연결을 처리하는 적절한 방법은 무엇입니까?

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions{ 
    . 
    . 
    . 
    receivedData = [[NSMutableData alloc] init]; 
} 

합니다.

-(void) dataFromWeb{ 
request = [[NSURLRequest alloc] initWithURL: url]; 
theConnection = [[NSURLConnection alloc] initWithRequest:request delegate:self]; 

if (theConnection) { 
    receivedData = [[NSMutableData data] retain]; 
    NSLog(@"** NSURL request sent !"); 
} else { 

    NSLog(@"Connection failed"); 
} 

.

- (void)connectionDidFinishLoading:(NSURLConnection *)connection 
{ 
    . 
    . 
    . 
    [theConnection release]; 
    [request release]; 

// Here - using receivedData 
[receivedData release]; 
} 

.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
     [receivedData setLength:0]; 
} 

.

- (void)connection:(NSURLConnection *)connection 
    didFailWithError:(NSError *)error 
{ 
    [theConnection release]; 
    [request release]; 
    [receivedData release]; 
} 

.

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    [receivedData appendData:data]; 
} 

.

if (theConnection) { 
    // Create the NSMutableData to hold the received data. 
    // receivedData is an instance variable declared elsewhere. 
    receivedData = [[NSMutableData data] retain]; 
} else { 
    NSLog(@"Connection failed"); 
} 

내가 이해하고 싶은 것은 :

  • 내가 다른 동시 된 URLRequest를 만들고 싶었 경우에, 나는 다른를 사용해야합니다 응용 프로그램에서 도로 아래로이 조각 (onButtonPressed)입니다 웹에서 도착하는 데이터가 검색시에 섞이지 않도록 연결해야합니까? 이 코드에서

  • , 무슨 일이 앱이 내가 receivedData=nil 내가

    if(receivedData!=nil) 
        [receivedData setLength:0]; 
    else 
        receivedData = [[NSMutableData data] retain]; 
    
  • 에 줄을 변경해야 보았다 추락 때로는 코드가 함수 didReceiveResponse() setLength:0의 라인에 충돌 것입니다
  • 이 라인이 무엇을하고 있는지 잘 모르겠다 receivedData = [[NSMutableData data] retain];

답변

1

나는이 연결을 처리하는 가장 쉬운 방법은 NSMutableData을 복제하고 있다고 생각. 나는 그런 식으로 사용하고 완벽하게 작동합니다. 방법에서 당신은 receivedData2을 요청하거나 receivedData

그리고 당신이 사용하는 경우는 잊지하지는 다음

receivedData2 = [[NSMutableData alloc] init]; 

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response 
{ 
    if (receivedData2) { 
     [receivedData2 setLength:0]; 
    } 
    else 
    { 
     [receivedData setLength:0]; 
    } 
} 

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data 
{ 
    if (receivedData2) { 
     [receivedData2 appendData:data]; 
    } 
    else {  
     [receivedData appendData:data]; 
    } 
} 

그리고 :

주먹 당신은 두 번째 연결을하려는 지점에서이 작업을 수행 수행

receivedData2=nil; 
[receivedData2 setLength:0]; 
0
  1. 당신 물론 것 다른 NSURLConnection이 필요합니다.
  2. 당신은 할 수 있지만 더 잘 알아낼 수 있습니다.
  3. NSMutableData 개체를 할당합니다. autoreleased 객체를 생성하고 유지하기 때문에 이것은 추한 코드처럼 보입니다. [NSMutableData new] 또는 [[NSMutableData alloc] init]으로 작성하십시오.
관련 문제