Alex
Alex

Reputation: 11147

How does multithread work in objective-c?

In the scenario in which i have a thread launched, can i still acces methods on the parent thread? Is there a specific way to call this methods? If so, what is it?

Note: in my scenario both thread are for data manipulation, they are not interface-related threads ( i know this was to be considered in .NET, don't know it they are in Objective-c).

Upvotes: 0

Views: 2535

Answers (3)

Nathan Day
Nathan Day

Reputation: 6037

If they are not interface stuff, or can result in some interface stuff you can call then you can just call then, and do any of the usual thread safety stuff you have to do in any language, like @syschronise(obj) or NSLock. But if it is stuff that will result in interface stuff then you will have to do as 'Srikar' wrote [self performSelectorOnMainThread:@selector(setDataCount:) withObject:count waitUntilDone:NO]; which will effectively place the message onto the NSRunLoop cue.

Upvotes: 1

dtuckernet
dtuckernet

Reputation: 7895

In this case, it is best to use Grand Central Dispatch (GCD) instead of working with NSThead or NSOperation directly.

Overview of Concurrency: http://developer.apple.com/library/ios/#documentation/General/Conceptual/ConcurrencyProgrammingGuide/Introduction/Introduction.html#//apple_ref/doc/uid/TP40008091

Intro to Grand Central Dispatch: http://cocoasamurai.blogspot.com/2009/09/guide-to-blocks-grand-central-dispatch.html

With your example, you can use nested calls into Grand Central Dispatch to achieve this functionality:

dispatch_queue_t backgroundQueue = dispatch_queue_create("com.example.exampleQueue", 0);

dispatch_async(backgroundQueue, ^{

    // operate on data in the background here
    NSData *stuff = [self doSomethingComplex];

    dispatch_async(dispatch_get_main_queue(), ^{
    // Perform Task back in the main thread
        [viewController updateStuff:stuff];
    });
});

This method is the preferred method for performing these kind of tasks. In addition, by utilizing blocks, it is also very easy to understand the code at a glance without having to example multiple methods within your class.

Upvotes: 4

Srikar Appalaraju
Srikar Appalaraju

Reputation: 73688

Threads by definition share the state of parent thread. In ObjectiveC, if you spawn a worker thread & want to call some method on main thread, this can be done like so-

[self performSelectorOnMainThread:@selector(someMethod:) withObject:nil waitUntilDone:NO];

Upvotes: 1

Related Questions