从另一个线程在主线程上运行方法 [英] Run method on main thread from another thread

查看:145
本文介绍了从另一个线程在主线程上运行方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的模型类必须从互联网上获取一些数据。所以我决定在另一个线程上运行它,所以ui不冻结。
所以当一个对象想要一些数据时,它首先使用这种类型的方法请求模型:

My model class has to get some data from the internet. So I decided to run it on another thread so the ui doesn't freeze. So when an object wants some data it first asks the model using a method of this type:

- (void)giveMeSomeData:(id)object withLabel:(id)label {
objectAsking= object;
theLabel= label;
NSThread* thread= [[NSThread alloc] initWithTarget:self selector:@selector(getTheDataFromInternet) object:nil];
[thread start];
}

- (void)getTheDataFromInternet {
//getting data...

theData= [dataFromInternet retain]; //this is the data the object asked for
[self returnObjectToAsker];
}

- (void)returnObjectToAsker {
[objectAsking receiveData:theData withLabel:theLabel];
}

因为我还是个新手,你能告诉我,模式?

As I'm still a newbie, can you tell me if it's a good pattern?

谢谢!

推荐答案

由于目前的情况, -returnObjectToAsker 将在后台执行绪。

As it currently stands, -returnObjectToAsker will be executed on the background thread.

您可能会对-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]

You'd probably be interested in -[NSObject performSelectorOnMainThread:withObject:waitUntilDone:].

或者如果你想使用Grand Central Dispatch(iOS 4+,Mac OS X 10.6+),你可以: / p>

Or if you wanted to something with Grand Central Dispatch (iOS 4+, Mac OS X 10.6+), you could do:

#import <dispatch/dispatch.h>

- (void)giveMeSomeData:(id)object withLabel:(id)label {
    dispatch_async(dispatch_get_global_queue(0,0), ^{
      //this runs on a background thread
      //get data from the internet
      dataFromTheInternet = ...;
      dispatch_async(dispatch_get_main_queue(), ^{
        [object receiveData:dataFromTheInternet withLabel:label];
        //this runs on the main thread.  Use theData
      });
    });
}

由于块捕获了他们的环境,你甚至不必保存 object 标签 into ivars。 :)

Since the blocks capture their environment, you wouldn't even have to save off object and label into ivars. :)

这篇关于从另一个线程在主线程上运行方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆