Intra-Process Communication in Objective C

走远了吗. 提交于 2019-12-11 08:09:49

问题


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?


回答1:


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




回答2:


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



回答3:


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



来源:https://stackoverflow.com/questions/5917772/intra-process-communication-in-objective-c

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!