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];
}

. アプリの途中には、このスニペット (onButtonPressed) があります。

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 を作成したい場合、Web から到着するデータが取得時に混同されないように、別の接続を使用する必要がありますか?

  • このコードでは、関数didReceiveResponse() の行でコードがクラッシュすることがありますsetLength:0。アプリがクラッシュしたときにreceivedData=nil、行を次のように変更する必要があります。

    if(receivedData!=nil)
       [receivedData setLength:0];
    else
       receivedData = [[NSMutableData data] retain];
    
  • この行が何をしているのかよくわかりませんreceivedData = [[NSMutableData data] preserve];

4

2 に答える 2

1

2 つの接続を処理する最も簡単な方法は、NSMutableData. 私はそのように使用していますが、私にとっては完璧に機能します。

最初に、2 番目の接続が必要なポイントでこれを行います。

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 または receivedData を要求します

そして、あなたがそれを使うときは、次のことを忘れないでください:

receivedData2=nil;
[receivedData2 setLength:0];
于 2012-11-22T10:46:43.947 に答える
0
  1. もちろん、別のNSURLConnection.
  2. あなたはそれを行うことができますが、それがすべきではないので、なぜそれが nil なのかをよく調べてください。
  3. 空のNSMutableDataオブジェクトを割り当てます。しかし、自動解放されたオブジェクトを作成して保持するため、これは私には醜いコードのように思えます。[NSMutableData new]または と書いた方がよいでしょう[[NSMutableData alloc] init]
于 2012-11-22T10:49:27.560 に答える