从另一个线程在主线程上运行方法
我的模型类必须从互联网获取一些数据。所以我决定在另一个线程上运行它,这样用户界面就不会冻结。 因此,当一个对象需要一些数据时,它首先使用这种类型的方法询问模型:
- (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];
}
由于我仍然是新手,你能告诉我这是否是一个好的模式?
谢谢!
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?
Thanks!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
你的设置几乎是正确的。您永远不想在主线程上启动任何类型的网络连接。
就目前而言,
-returnObjectToAsker
将在后台线程上执行。您可能会对
-[NSObject PerformSelectorOnMainThread:withObject:waitUntilDone:]
。或者,如果您想使用 Grand Central Dispatch(iOS 4+、Mac OS X 10.6+)进行某些操作,您可以这样做:
由于块捕获了它们的环境,因此您甚至不必保存
对象
和label
到 ivars 中。 :)Your setup is pretty much correct. You never want to initiate any sort of network connection on the main thread.
As it currently stands,
-returnObjectToAsker
will be executed on the background thread.You'd probably be interested in
-[NSObject performSelectorOnMainThread:withObject:waitUntilDone:]
.Or if you wanted to something with Grand Central Dispatch (iOS 4+, Mac OS X 10.6+), you could do:
Since the blocks capture their environment, you wouldn't even have to save off
object
andlabel
into ivars. :)