Abhinav
Abhinav

Reputation: 38162

Intra-Process Communication in Objective C

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?

Upvotes: 1

Views: 1155

Answers (3)

AechoLiu
AechoLiu

Reputation: 18408

  • 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.

Upvotes: 2

Rayfleck
Rayfleck

Reputation: 12106

You can have the thread post an NSNotification that the main thread is listening for (observing) and pass information in the NSNotification's object.

Upvotes: 1

David Neiss
David Neiss

Reputation: 8237

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

Upvotes: 2

Related Questions