我試圖在後臺運行一個方法,但它仍然阻止程序。 這是我的代碼:Objective-C中的多線程
- (void)viewDidLoad
{
[super viewDidLoad];
self.MessagesList=[[MessagesArray alloc] init];
[self performSelectorInBackground:@selector(backgroundMethod) withObject:nil];
}
-(void)backgroundMethod
{
if ([MessagesList updateFromServer]){
[self.Table reloadData];
CFRunLoopRun();
}
}
雖然updateFromServer將HTTP請求發送到服務器,並等待響應時,服務器延遲以10秒的反應,其結果是,整個程序被延遲10秒太。你能糾正我嗎?
更新:我添加了一個runloop行,但問題依然存在。 HTTP請求是異步的,但仍然是 - 整個程序一直等到服務器響應。這是我的updateFromServer方法:
responseData = [NSMutableData data];
[self setBaseURL:[NSURL URLWithString:@"http://localhost:8000/messages/views/new_messages/"]];
NSURLRequest *request =
[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8000/messages/views/new_messages/"]];
NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
return TRUE;
我怎樣才能使它成爲異步的真實?
如何使用NSThread來代替? – 2011-12-26 12:08:23
我也試過了。沒有什麼變化。感謝 – 2011-12-26 12:28:40