处理网络连接的正确方法是什么?

时间:2012-11-22 10:24:11

标签: objective-c ios xcode

我的应用正在使用网络连接,如下所示:

- (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,我是否需要使用不同的连接,以便从网上传来的数据在检索时不会混淆?

  • 在这段代码中,有时代码会在函数 didReceiveResponse() setLength:0的行上崩溃,当应用程序崩溃时我看到{{1我应该将行更改为

    receivedData=nil
  • 我不太确定这条线在做什么 receivedData = [[NSMutableData data] retain];

2 个答案:

答案 0 :(得分:1)

我认为处理2个连接的最简单方法是复制NSMutableData。我用这种方式,它对我来说很完美。

在你想要第二次连接时,你要这样做:

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

然后,在您请求receiveData2或receivedData

的方法中

当你使用它时别忘了:

receivedData2=nil;
[receivedData2 setLength:0];

答案 1 :(得分:0)

  1. 您当然需要不同的NSURLConnection
  2. 你可以这样做,但最好找出,为什么它是零,因为它不应该。
  3. 它分配一个空的NSMutableData对象。但这对我来说似乎是丑陋的代码,因为你创建了一个自动释放的对象并保留它。最好写[NSMutableData new][[NSMutableData alloc] init]