开发者

iphone sdk communicate between thread

My application has a second running thread. I need to achieve the following :

  • Stop the separate thread gracefully from the main application thread
  • Call a function on the main thread from the second thread to signal a result has been found and pass it to the main one.

I've found the following for the first task : share a gl开发者_JAVA技巧obal variable between the 2 threads ? No idea how to achieve the second task. (NSNotificationCenter doesn't allow to pass objects ...)

I'm lunching the second thread like this [NSThread detachNewThreadSelector:@selector(backGroudTask) toTarget:self withObject:nil];

Thanks


I'm still searching for the best answer to this, but here is what I do:

Use NSLock to create a lock that prevents me from accessing the same variable on both threads. Then use a BOOL to see if the main thread wants to initiate a stop.

in main thread do this


[myLock lock];
exitFlag = YES;
[myLock unlock];

in the other thread do this

endMe = NO;

while(!endMe)
{
  // do your task stuff

  [myLock lock];
  endMe = exitFlag;
  [myLock unlock];
}

For the second part of your question use the following:

[self performSelectorOnMainThread:@selector(your_selector_name) withObject:nil waitUntilDone:false];

This will cause the your selector routine to run on the main thread.

Hope this helps


(NSNotificationCenter doesn't allow to pass objects ...)

it does, but you have to add them to the userinfo of the notification

NSDictionary *userInfo = [NSDictionary dictionaryWithObject:myObject forKey:@"object"];
[[NSNotificationCenter defaultCenter] postNotificationName:@"myNotification" object:self userInfo:userInfo];

- (void)foo:(NSNotification *)notification {
    id object = [[notification userInfo] objectForKey:@"object"];
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜