0

我正在通过创建 NSOperation 并同步打开 NSURLConnections 来实现与服务器的后端数据加载。

这段代码在模拟器和设备上都运行良好,直到我添加了一个进度条,通知返回到主线程。

- (void)start {
     // stop execution if it's cancelled

     if([self isCancelled]) {
          [self willChangeValueForKey:@"isFinished"];
          finished = YES;
          [self didChangeValueForKey:@"isFinished"];
          return;
     } 

     // If the operation is not canceled, begin executing the task.
     [self willChangeValueForKey:@"isExecuting"];
     [NSThread detachNewThreadSelector:@selector(main ) toTarget:selfwithObject:nil];
     executing = YES;
     [self didChangeValueForKey:@"isExecuting"];
}

现在我在同步调用中遇到 EXC_BAD_ACCESS 崩溃。

NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"%@/index.php", rootURL]];
NSMutableURLRequest *urlRequest = [NSMutableURLRequest requestWithURL:url];
[urlRequest setHTTPMethod:@"POST"];
[urlRequest setHTTPBody:[bodyString dataUsingEncoding:NSUTF8StringEncoding]];
[[NSURLCache sharedURLCache] removeAllCachedResponses];
[[NSURLCache sharedURLCache] setMemoryCapacity:0];
[[NSURLCache sharedURLCache] setDiskCapacity:0];

NSError *error = nil;
NSURLResponse *response = nil;
receivedData = [[NSURLConnection sendSynchronousRequest:urlRequest returningResponse:&response error:&error] mutableCopy];

堆栈跟踪运行如下:

#0  0x3430debc in objc_msgSend ()
#1  0x3136f996 in NSPopAutoreleasePool ()
#2  0x31374160 in -[NSAutoreleasePool release] ()
#3  0x331a0408 in _UIApplicationHandleEvent ()
#4  0x325339c4 in PurpleEventCallback ()
#5  0x3147a52a in CFRunLoopRunSpecific ()
#6  0x31479c1e in CFRunLoopRunInMode ()
#7  0x3314ec08 in -[UIApplication _run] ()
#8  0x3314d230 in UIApplicationMain ()
#9  0x00002ab0 in main (argc=1, argv=0x2ffff504)

使用 NSZombieEnabled,我得到

*** -[NSDateComponents release]: message sent to deallocated instance 0x172fd0

我知道正在建立连接(查看服务器日志,请求正在通过)。在 NSURLConnection 之前的 NSOperation 代码中的任何地方都没有分配 NSDateComponent 对象。

我一直在努力弄清楚我突然对 NSURLConnection 做错了什么,让它如此讨厌我。

任何帮助是极大的赞赏!

4

2 回答 2

1

虽然我不确切知道您的问题是什么,但我知道我曾经在使用 NSURLConnection 时也遇到过随机错误和崩溃。然后我找到了 ASIHTTPRequest并且再也没有回头。它是 NSURLConnection 的替代品,并且脱离了 CFNetwork。它非常稳定(我在所有项目中都使用它)并附带了许多好东西,例如内置的进度条支持和部分下载恢复。它甚至可以直接写入磁盘以节省 RAM,这在 iPhone 中很重要。

于 2009-09-18T04:02:32.847 回答
0

我也在开发者论坛上发布了这个问题,并得到了删除并发的建议。我删除了违规行:

[NSThread detachNewThreadSelector:@selector(main ) toTarget:selfwithObject:nil];

我也停止了覆盖 start,只覆盖了 main。

NSURLConnection 停止崩溃。

于 2009-09-19T02:14:42.497 回答