使用异步 NSURL 获取警告



我试图避免这个警告,我正在使用NSURLConnection

-(void)goGetData{
    responseData = [NSMutableData data];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://somefile.php"]];
    [[NSURLConnection alloc]initWithRequest:request delegate:self];
}
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    [responseData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    [responseData appendData:data];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    //label.text = [NSString stringWithFormat:@"Connection failed: %@", [error description]];
    NSLog(@"Connection failed: %@",error);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    NSString *responseString = [[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding];
    NSMutableArray *qnBlock = [responseString JSONValue];
    for (int i = 0; i < [qnBlock count]; i++){
        NSLog(@"%@",[qnBlock objectAtIndex:i]);
    }
}

警告在行:

[[NSURLConnection alloc]initWithRequest:request delegate:self];

警告是:

Expression result unused. 

整个代码运行良好,但我只是在采取预防措施。

这两种方法都分配一个对象。

随着分配,

[[NSURLConnection alloc]initWithRequest:request delegate:self];

您有责任发布它。

使用connectWithRequest,

[NSURLConnection connectionWithRequest:request delegate:self];

它由自动释放池保留。我的猜测是,由于它由自动发布池保留,因此不需要句柄来释放它,并且编译器对自动发布池具有句柄感到满意。

使用 alloc,编译器可能希望您保留一个句柄以供以后发布。因此,它将其标记为警告。

事实是,委托方法获取句柄,无论您是否显式保留一个句柄。因此,可以使用传递给委托方法的句柄来释放它。警告确实是虚假的,但它只是一个警告。

您可以执行以下操作:

[NSURLConnection connectionWithRequest:request delegate:self];

而不是:

[[NSURLConnection alloc]initWithRequest:request delegate:self];

相关内容

最新更新