Intra-Process Communication in Objective C
I want to know how can a child thread talk to parent thread in Objective C. I am开发者_C百科 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.
Usually you have the other thread run a selector back on the main thread and share info through an ivar.
-(void)performSelectorOnMainThread:(SEL)aSelector withObject:(id)arg waitUntilDone:(BOOL)wait
You can have the thread post an NSNotification that the main thread is listening for (observing) and pass information in the NSNotification's object.
精彩评论