Kami
Kami

Reputation: 6059

iphone sdk communicate between thread

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

I've found the following for the first task : share a global 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

Upvotes: 0

Views: 663

Answers (2)

TejasSoft
TejasSoft

Reputation: 151

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

Upvotes: 1

Matthias Bauch
Matthias Bauch

Reputation: 90117

(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"];
}

Upvotes: 1

Related Questions