我需要对某个url进行多次https调用。因此,我做这样的事情iOS:使用performSelectorInBackground发送同步请求
//ViewController Source
-(IBAction) updateButton_tapped {
[self performSelectorInBackground:@selector(updateStuff) withObject:nil];
}
-(void) updateStuff {
// do other stuff here...
NSMutableURLRequest* request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:self.url]];
[request setHTTPMethod:@"POST"];
NSData *postData = [[Base64 encodeBase64WithData:payload] dataUsingEncoding:NSASCIIStringEncoding];
[request setHTTPBody:postData];
NSURLResponse* response = [[NSURLResponse alloc] init];
NSData* data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//Process the recieved data...
//Setup another synchronous request
data = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//Process data
//do this another 4 times (note for loop cannot be use in my case ;))
//Finally update some view controllers
[[NSNotificationCenter defaultCenter] postNotificationName:@"NotificationIdentifier" object:self];
}
所以这个代码的问题是,它随机崩溃(并不总是频繁)。日志中没有调试输出。有时我的整个应用程序冻结,或者只是崩溃了整个程序。但是如果我在主线程上运行它,它永远不会崩溃。因此,我认为代码是正确的,我想现在它与iphone上的线程有关。
以这种方式运行代码时会发生什么问题,以及可能导致随机崩溃的原因?
感谢您的回答。但我如何在我的情况下使用autorelease块。我不知道autorelease附加。 – toom 2012-02-13 17:30:26
@toom当你在后台线程上执行时,你需要一个自动释放池。你的选择是将调度切换到为你管理这个池的Grand Central Dispatch,或者简单地把方法的主体放在'@ autoreleasepool'块中。我已经为你回答了后者的一个例子。 – 2012-02-13 17:56:30
谢谢你的帮助。 – toom 2012-02-13 20:25:59