我的應用程序正在使用的網絡連接在這裏:處理網絡連接的正確方法是什麼?
- (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];