【发布时间】:2023-03-29 10:04:02
【问题描述】:
我是 iPhone 新手,
我正在按照苹果here 的建议创建 NSURLConnection
但是当我关闭我的视图时我的应用程序崩溃了,我尝试了NSZombieEnabled 的概念,它显示了-[CALayer release]: message sent to deallocated instance 0x68b8f40
我在Webview 中显示一个网页,当用户点击webview 中的下载链接时,shouldStartLoadWithRequest 方法将在此方法中被调用,我正在创建NSURLConnection。
这是我的代码 sn-p,
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data1
{
[receivedData appendData:data1];
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
DirPath=[self applicationDocumentsDirectory];
NSLog(@"DirPath=%@",DirPath);
[receivedData writeToFile:DirPath atomically:YES];
UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:@"Download Complete !"
message:nil delegate:nil
cancelButtonTitle:@"OK"
otherButtonTitles:nil];
[Alert show];
[Alert release];
// release the connection, and the data object
[connection release];
[receivedData release];
}
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error1
{
[connection release];
[receivedData release];
// inform the user
NSLog(@"Connection failed! Error - %@ %@",
[error1 localizedDescription],
[[error1 userInfo] objectForKey:NSURLErrorFailingURLStringErrorKey]);
}
- (BOOL)webView:(UIWebView*)webView shouldStartLoadWithRequest:(NSURLRequest*)request navigationType:(UIWebViewNavigationType)navigationType {
//CAPTURE USER LINK-CLICK.
Durl=[[url absoluteString]copy];
//Checking for Duplicate .FILE at downloaded path....
BOOL success =[[NSFileManager defaultManager] fileExistsAtPath:path];
lastPath=[[url lastPathComponent] copy];
if (success) //if duplicate file found...
{
UIAlertView* Alert = [[UIAlertView alloc] initWithTitle:@"This FILE is already present in Library."
message:@"Do you want to Downlaod again ?" delegate:self
cancelButtonTitle:nil
otherButtonTitles:@"Yes",@"No",nil];
[Alert show];
[Alert release];
}
else //if duplicate file not found directly start download...
{
// Create the request.
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:Durl]
cachePolicy:NSURLRequestUseProtocolCachePolicy
timeoutInterval:60.0];
// create the connection with the request and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
// Create the NSMutableData to hold the received data.
receivedData = [[NSMutableData data] retain];
} else {
NSLog(@"Inform the user that the connection failed.");
}
return YES;
}
我们将不胜感激。
【问题讨论】:
-
评论此行并检查[连接释放];
-
已经试过了,但是不行。
-
你也评论了receivedData吗?
-
是的,我尝试了两种可能性,有评论和没有评论,但仍然崩溃。
-
NSLog(@" connection %p",connection); NSLog(@"receivedData %p",receivedData); NSLog(@"webView %p",webView);打印对象地址并检查是哪一个导致了崩溃。并且还在 connection 和 receivedData 对象上调用 retain。
标签: iphone ipad nsurlconnection release exc-bad-access