xcode 异步 NSURLConnection 抛出 EXC_BAD_ACCESS
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2802180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Asynchronous NSURLConnection Throws EXC_BAD_ACCESS
提问by Sheehan Alam
I'm not really sure why my code is throwing a EXC_BAD_ACCESS, I have followed the guidelines in Apple's documentation:
我不太确定为什么我的代码会抛出 EXC_BAD_ACCESS,我遵循了 Apple 文档中的指南:
-(void)getMessages:(NSString*)stream{
NSString* myURL = [NSString stringWithFormat:@"http://www.someurl.com"];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:[NSURL URLWithString:myURL]];
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
receivedData = [[NSMutableData data] retain];
} else {
NSLog(@"Connection Failed!");
}
}
And my delegate methods
还有我的委托方法
#pragma mark NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// This method is called when the server has determined that it
// has enough information to create the NSURLResponse.
// It can be called multiple times, for example in the case of a
// redirect, so each time we reset the data.
// receivedData is an instance variable declared elsewhere.
[receivedData setLength:0];
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
// Append the new data to receivedData.
// receivedData is an instance variable declared elsewhere.
[receivedData appendData:data];
}
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
// release the connection, and the data object
[connection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];
// inform the user
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
// release the connection, and the data object
[connection release];
[receivedData release];
}
I get an EXC_BAD_ACCESS on didReceiveData. Even if that method simply contains an NSLog, I get the error.
我在 didReceiveData 上得到一个 EXC_BAD_ACCESS。即使该方法只包含一个 NSLog,我也会收到错误消息。
Note: receivedData is an NSMutableData* in my header file
注意:receiveData 是我头文件中的 NSMutableData*
采纳答案by Manjunath
Use NSZombieEnabledbreak point and check which is the freed object.
使用NSZombieEnabled断点并检查哪个是释放的对象。
Also check:
还要检查:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
if ([response expectedContentLength] < 0)
{
NSLog(@"Connection error");
//here cancel your connection.
[connection cancel];
return;
}
}
回答by JeremyP
I have followed the guidelines in Apple's documentation:
我遵循了 Apple 文档中的指南:
That is not true. In both of the following, you break the rules:
那不是真的。在以下两种情况下,您都违反了规则:
- (void)connection:(NSURLConnection *)connection
didFailWithError:(NSError *)error
{
// release the connection, and the data object
[connection release];
// receivedData is declared as a method instance elsewhere
[receivedData release];
// inform the user
NSLog(@"Connection failed! Error - %@ %@",
[error localizedDescription],
[[error userInfo] objectForKey:NSErrorFailingURLStringKey]);
}
- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
// do something with the data
// receivedData is declared as a method instance elsewhere
NSLog(@"Succeeded! Received %d bytes of data",[receivedData length]);
// release the connection, and the data object
[connection release];
[receivedData release];
}
In both cases, you do notobtain the connection
object with alloc
, a method beginning with new
or containing copy
. You do not own connection
in these methods. You must not release it in these methods.
在这两种情况下,您都不会connection
通过alloc
、 以 开头new
或包含的方法获取对象copy
。你不拥有connection
这些方法。您不得在这些方法中释放它。
It seems to me slightly dodgy that you are releasing receivedData there too. I suggest you immediately set the instance variable to nil after you release it.
在我看来,你也在那里发布了 receivedData 有点狡猾。我建议您在释放实例变量后立即将其设置为 nil。
[receivedData release];
receivedData = nil;
That way, it won't get accidentally released moere than once.
这样,它不会被意外释放不止一次。
回答by deanWombourne
If you're getting the error on didRecieveData regardless of the code inside it, it looks like your delegate has been freed?
如果您在 didRecieveData 上收到错误,而不管其中的代码如何,您的委托似乎已被释放?
I'd check that the object that contains the getMessages method isn't being released (or autoreleased) before the connection has dfinished getting data.
在连接完成获取数据之前,我会检查包含 getMessages 方法的对象是否没有被释放(或自动释放)。
EDIT: The comments below show that my above answer is wrong :)
编辑:下面的评论表明我上面的答案是错误的:)
The problem was in the recievedData variable - it was being released early. Mark suggests releasing it in the dealloc method of the object that creates the connection so he deserves all the credit for this!
问题出在 recievedData 变量中——它被提前发布了。Mark 建议在创建连接的对象的 dealloc 方法中释放它,因此他应该为此付出一切!
There's one slight thing to lookout for there - if you release the recievedData in the dealloc method, you will leak memory if you call getMessages more than once. You will need to change getMessages slightly to this :
有一件小事需要注意——如果你在 dealloc 方法中释放 recievedData,如果你多次调用 getMessages 就会泄漏内存。您需要将 getMessages 稍微更改为:
...
if (theConnection) {
[recievedData release]; // If we've been here before, make sure it's freed.
receivedData = [[NSMutableData data] retain];
} else {
...
回答by fsakar
I got the same error when debugging with device although there was no problem in simulation. Adding the following line of code after releasing receivedData solved the problem:
尽管在模拟中没有问题,但在使用设备进行调试时我遇到了同样的错误。释放receiveData后添加下面这行代码就解决了问题:
receivedData = nil;
回答by coco
Commenting on JeremyP, where he says that "In both of the following, you break the rules": Sheehan Alam is following Apple's code (actually, cut'n'paste) found here.
在评论 JeremyP 时,他说“在以下两个方面,你都违反了规则”:Sheehan Alam 正在遵循 Apple 的代码(实际上是剪切和粘贴)here。
I'd also like to add (and this is something that wasn't well answered here) that the 'build and analyze' flags a "potential leak" on the NSURLConnection (which is initiated with a "[NSURLConnection alloc]"). But if one puts in a [theConnection release] on the NSURLConnection, in the same method, it will crash.
我还想补充一点(这里没有很好地回答这个问题)“构建和分析”标记了 NSURLConnection 上的“潜在泄漏”(由“[NSURLConnection alloc]”启动)。但是如果在 NSURLConnection 上放一个 [theConnection release],同样的方法,它会崩溃。
So we have something that seems to defy the 'rules' for memory management, yet works (afaik) and is in Apple's documentation..
所以我们有一些东西似乎违反了内存管理的“规则”,但有效(afaik)并且在 Apple 的文档中。
回答by coco
I got EXC_BAD_ACCESS on Asynchronous call at NSURLConnection. The code is generated by http://www.sudzc.com
我在 NSURLConnection 的异步调用中得到了 EXC_BAD_ACCESS。代码由http://www.sudzc.com生成
I needed to add a retain to
我需要添加一个保留到
receivedData = [[NSMutableData data] retain];
receivedData = [[NSMutableData data] retain];
and the callback methods doesn't get bad access signal anymore.
并且回调方法不会再收到糟糕的访问信号。
if I add the
if ([response expectedContentLength] < 0) { NSLog(@"Connection error"); //here cancel your connection. [connection cancel]; return; }
如果我添加
if ([response expectedContentLength] < 0) { NSLog(@"Connection error"); //here cancel your connection. [connection cancel]; return; }
than all my webservices are canceled, otherwise works perfectly.
比我所有的网络服务都被取消,否则效果很好。
回答by Hafthor
While it doesn't answer the full question, I've run into this error a couple of times because I set the request's HTTPBody to an NSString instead of a NSData. Xcode tried to warn me.
虽然它没有回答完整的问题,但我遇到过几次这个错误,因为我将请求的 HTTPBody 设置为 NSString 而不是 NSData。Xcode 试图警告我。