私のアプリは、次のようにネットワーク接続を使用しています:
- (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];