目标C中的进程间通信 [英] Intra-Process Communication in Objective C
问题描述
我想知道如何一个子线程与目标C中的父线程谈话。我从我的主线程产生一个线程,并想要关于一些动作的主线程并继续。
- 如果在子线程中发布NSNotification,接收通知并在
下执行与发件人相同的线程
。 - 线程之间的信息可以通过共享内存传输,例如:struct,primitive types(int,CGFloat等)。
-
线程之间的信息可以通过 threadDictionary 属性。我更喜欢使用这个来注册一些状态变量。例如,当滚动时,我将设置以下。
NSMutableDictionary * dictInfo = [NSThread mainThread] .threadDictionary;
[dictInfo setObject:[NSNumber numberWithbool:YES] forKey:_kThreadPause];
当工作线程看到_kThreadPause设置为YES时,它将进入休眠状态。
BOOL bPause = [[[[NSThread mainThread] .threadDictionary objectForKey:_kThreadPause] boolValue];
if(bPause)[NSThread sleepForTimeInterval:0.1];
-
正如DavidNeiss所说,您可以使用NSObject的方法来执行选择器主线程或子线程。
如果有时间,可以阅读线程编程指南。
I want to know how can a child thread talk to parent thread in Objective C. I am spawning a thread from my main thread and want to intimate main thread about some action and keep continuing. How to achieve this?
- If you post a NSNotification in the child thread, the receiver will receive the notification and execute under
the same thread
as the sender. The apple document said that and marked as a note. - The information between threads can be transfered by a shared memory, ex: a struct, primitive types (int, CGFloat, etc).
The information between thread can be transfered by threadDictionary property of NSThread. I prefer to use this to register some status variables. For example, when scrolling, I will set following.
NSMutableDictionary *dictInfo = [NSThread mainThread].threadDictionary; [dictInfo setObject:[NSNumber numberWithbool:YES] forKey:_kThreadPause];
The worker thread will go to sleep when it see the _kThreadPause is set to YES.
BOOL bPause = [[[NSThread mainThread].threadDictionary objectForKey:_kThreadPause] boolValue]; if (bPause) [NSThread sleepForTimeInterval:0.1];
As DavidNeiss said, you can use methods of NSObject to perform selector on main thread or child thread.
If you have time, you can read threading programming guide.
这篇关于目标C中的进程间通信的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!