objective-c – 在目标c中执行选择器主线程的最佳方法?

objective-c – 在目标c中执行选择器主线程的最佳方法?,第1张

概述我正在为iPhone编写客户端 – 服务器应用程序.我有一个关于线程的问题.当我从设备访问我的在线数据库时,我需要在单独的线程上执行此 *** 作以不冻结UI /主线程.但是当响应我从数据库中获取的数据时,我在主线程上调用此方法:performSelectorOnMainThread.问题是,这只能让我向方法(WithObject)发送一个参数/对象,有时候我想传递更多的参数.关于它的另一件事是我必须通过 我正在为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 ...

它对您调用的方法的参数数量没有任何限制.

总结

以上是内存溢出为你收集整理的objective-c – 在目标c中执行选择器主线程的最佳方法?全部内容,希望文章能够帮你解决objective-c – 在目标c中执行选择器主线程的最佳方法?所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/web/1059078.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-05-25
下一篇 2022-05-25

发表评论

登录后才能评论

评论列表(0条)

保存