我需要對某個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