首先,你们都在为保存代码创建一个新线程,然后异步使用 NSUrlConnection。NSUrlConnection 在它自己的实现中也会派生另一个线程并在新创建的线程上给你回电,这通常不是你想要做的事情。我假设您只是想确保您的 UI 在保存时不会阻塞...
NSUrlConnection 也有同步版本,它会阻塞你的线程,如果你想启动自己的线程来做事,最好使用它。签名是
+ sendSynchronousRequest:returningResponse:error:
然后,当您收到响应时,您可以回调您的 UI 线程。像下面这样的东西应该可以工作:
- (void) beginSaving {
// This is your UI thread. Call this API from your UI.
// Below spins of another thread for the selector "save"
[NSThread detachNewThreadSelector:@selector(save:) toTarget:self withObject:nil];
}
- (void) save {
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
// ... calculate your post request...
// Initialize your NSUrlResponse and NSError
NSUrlConnection *conn = [NSUrlConnection sendSyncronousRequest:postRequest:&response error:&error];
// Above statement blocks until you get the response, but you are in another thread so you
// are not blocking UI.
// I am assuming you have a delegate with selector saveCommitted to be called back on the
// UI thread.
if ( [delegate_ respondsToSelector:@selector(saveCommitted)] ) {
// Make sure you are calling back your UI on the UI thread as below:
[delegate_ performSelectorOnMainThread:@selector(saveCommitted) withObject:nil waitUntilDone:NO];
}
[pool release];
}