我的应用程序正在使用网络连接,如下所示:
- (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
的行上崩溃,当应用程序崩溃时我看到receivedData=nil
我应该将行更改为if(receivedData!=nil) [receivedData setLength:0]; else receivedData = [[NSMutableData data] retain];
我不太确定这条线在做什么receivedData = [[NSMutableData data] retain];