繁体   English   中英

在目标c中执行选择器主线程的最佳方法是什么?

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM