首页 文章

NSURLRequest autorelease:崩溃

提问于
浏览
0

我在发布NSMutableURLRequest对象时遇到问题 . 应用程序在请求对象的重新分配期间崩溃 .

该对象是通过[[NSMutableURLRequest alloc] initWithURL:my_http_url]创建的;

作为主流控制流,我尝试释放连接对象以响应被调用的connectionDidFinishLoading处理程序 .

起初我尝试在connectionDidFinishLoading处理程序内自动释放NSMutableURLRequest . 这导致崩溃,所以我认为这可能是因为连接类在调用connectionDidFinishLoading之前在内部推送自动释放池,并且仍然希望连接对象在处理程序返回时有效,因此不可能在connectionDidFinishLoading中释放或自动释放连接对象 .

如果我根本不释放NSMutableURLRequest,根据Instruments,它会泄漏参考计数1 .

因此,我决定通过触发NSRunLoop事件来执行延迟释放,该事件自动释放传递给它的NSMutableURLRequest . 这仍然会导致崩溃 .

在调用autorelease之前,retainCount为1 .

崩溃堆栈是:

0   0x9448aedb in objc_msgSend
#1  0x04a47ce0 in ??
#2  0x02e51501 in HTTPMessage::~HTTPMessage
#3  0x02945621 in _CFRelease
#4  0x02e516a9 in HTTPRequest::~HTTPRequest
#5  0x02e50967 in URLRequest::~URLRequest
#6  0x02945621 in _CFRelease
#7  0x0032fb70 in -[NSURLRequestInternal dealloc]
#8  0x0032fb1a in -[NSURLRequest dealloc]
#9  0x002f27a5 in NSPopAutoreleasePool
#10 0x003b5dd0 in __NSFirePerformTimer
#11 0x0299e8a2 in __CFRunLoopDoObservers
#12 0x0296a39e in CFRunLoopRunSpecific
#13 0x0296a048 in CFRunLoopRunInMode
#14 0x031d289d in GSEventRunModal
#15 0x031d2962 in GSEventRun
#16 0x0058ede1 in UIApplicationMain
#17 0x00002b9c in main at main.m:14

谢谢你的建议 .

3 回答

  • 0

    使用 NSDebugEnabled/NSZombieEnabled/NSAutoreleaseFreedObjectCheckEnabled 后我发现了问题:

    的结果

    http_url = [NSURL URLWithString:...]
    

    应该保留或不自行释放 .

  • 1

    尝试使用以下方法将其实例化为自动释放的对象:

    [NSMutableURLRequest requestWithURL:my_http_url];
    
  • 0

    我相信在这种情况下,仪器对任何跟踪都没有用,因为应用程序崩溃然后自动重启(它是iPad / iPhone应用程序),因此所有的仪器历史记录都消失了 .

    我没有看到将NSMutableURLRequest实例化为自动释放的对象,因为它需要在跨越多个空闲循环周期的异步调用期间保留 . NSURLConnection可以在内部保留或不保留,但保持额外的安全参考不应该受到伤害 .

    初始化代码归结为基本上如下:

    rq-> url_encoded = [url_encode(rq-> url)retain]; rq-> http_url = [NSURL URLWithString:rq-> url_encoded]; rq-> http_request = [[NSMutableURLRequest alloc] initWithURL:rq-> http_url]; [rq-> http_request setHTTPMethod:@“GET”]; NSArray * availableCookies = [rq-> service.CookieJar cookiesForURL:rq-> http_url]; NSDictionary * headers = [NSHTTPCookie requestHeaderFieldsWithCookies:availableCookies]; [rq-> http_request setAllHTTPHeaderFields:headers]; rq-> http_connection = [NSURLConnection alloc]; [rq-> http_connection initWithRequest:rq-> http_request委托:rq startImmediately:YES];

    发布过程是connectionDidFinishLoading调用[rq-> http_connection cancel]和[rq autorelease],后者最终导致:

    // [http_request autorelease]; // delayedAutoRelease(http_request); [http_connection autorelease]; [http_url autorelease]; [url release]; [url_encoded release]; [回复发布];

    请注意,[响应发布]只是将didReceiveResponse中执行的前一个[响应保留]配对 .

    如果我将前两行注释掉,NSURLRequest会泄漏,每个仪器的引用计数为1,这是唯一发现的泄漏 .
    每当我尝试以上述方式自动释放http_request时,就会发生崩溃 .

相关问题