[英]Objective c: Bad access error when using performSelectorOnMainThread
[英]Best way to performselectoronmainthread in objective c?
我正在為iPhone編寫客戶端 - 服務器應用程序。 我有一個關於線程的問題。 當我從設備訪問我的在線數據庫時,我需要在單獨的線程上執行此操作以不凍結UI /主線程。 但是當響應我從數據庫中獲取的數據時,我在主線程上調用此方法:performSelectorOnMainThread。 問題是,這只允許我向方法(WithObject)發送一個參數/對象,有時我有更多我想傳遞的參數。 關於它的另一件事是我必須通過這一個對象。 如果我發現應用程序崩潰,我無法通過nil。
這是我今天的代碼..我擔心我正在使用這些方法並以錯誤的方式進行操作。
- (IBAction)testServerAction:(id)sender {
[self.imageView setHidden:YES];
[self.activityView setHidden:NO];
[self.activityView startAnimating];
dispatch_queue_t testServer = dispatch_queue_create("Test-Server-Thread", NULL);
dispatch_async(testServer, ^{
if ([self.arrayWithServerConnections count] > 0)
{
NSString *messageToShow;
if ([self testServerMethod])
{
messageToShow = @"Server is working!";
[self performSelectorOnMainThread:@selector(showMessageBoxWithString:) withObject:messageToShow waitUntilDone:YES];
[self performSelectorOnMainThread:@selector(threadedUIActivityRemover:) withObject:nil waitUntilDone:YES];
}else
{
messageToShow = @"Server is NOT working!";
[self performSelectorOnMainThread:@selector(showMessageBoxWithString:) withObject:messageToShow waitUntilDone:YES];
[self performSelectorOnMainThread:@selector(threadedUIActivityRemover:) withObject:nil waitUntilDone:YES];
}
}
});
dispatch_release(testServer);
}
-(void)threadedUIActivityRemover:(NSString *)string
{
[self.imageView setHidden:NO];
[self.activityView setHidden:YES];
[self.activityView stopAnimating];
}
這是一個很好的方法嗎,除了performSelectorOnMainThread之外還有什么可以指向我的,那更好嗎?
正如你所看到的,在這個例子中我將nil傳遞給NSString參數,因為我必須傳遞一些東西,如果我沒有NSString作為方法中的arg,應用程序在傳遞nil時崩潰了evan。為什么會這樣?請讓我對此更清楚一點!
//謝謝!
好吧,你已經在使用dispatch_async
。 然后你應該使用
dispatch_async(dispatch_get_main_queue(),^ { ... } );
從你的后台線程內部執行主線程上的事情。 例如,
if ([self testServerMethod])
{
dispatch_async(dispatch_get_main_queue(),^ {
[self showMessageBoxWithString: @"Server is working!"];
[self threadedUIActivityRemover:nil];
} );
}else ...
它對您調用的方法的參數數量沒有任何限制。
傳遞集合,例如未歸檔對象的字典。
您還可以使用NSInvocation
。
因為你傳遞實例變量,另一個選擇是傳遞self並使自己的線程安全。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.