Search code examples
iphoneiosobjective-ccocoa-touchdispatch-async

How to do GUI action in thread - IOS


I have a thread which will call many of my interface functions.. When it call I need to do some GUI action, As I aware GUI need to be done in main thread, still now I was using

            dispatch_async(dispatch_get_main_queue(), ^{
                // Some method call...
            });

It works fine for most of the cases, still I am facing problem here.. for e.g... my interface function is like below...

        void interface_fun(char *name, int user_id) {
                dispatch_async(dispatch_get_main_queue(), ^{
                    gui_acton_with_name(name, user_id);
                });
         }

Now the name pointer is most of the time I got nil within dispatch call(I guess I am loosing data here), I tried with performselectoronMainthread method.. But I don't know how to use this with multiple parameter..

Any idea thanks..


Solution

  • I'm posting this as an answer because it's too hard to put this into a comment, but if you use performSelectorOnMainThread:withObject:waitUntilDone: you can wrap your two bits of information into a dictionary (or an array, but a dictionary works better because you can access the information by name):

    NSDictionary *info = @{ @"name" : @(name), @"user_id", @(user_id) };
    [self performSelectorOnMainThread:@selector(someMethod:) withObject:info waitUntilDone:NO];
    

    And then in your method (iOS 6 only unless you revert to oldschool objectForKey:):

    - (void) someMethod:(NSDictionary *) info
    {
        NSString *name = info[@"name"];
        NSNumber *user_id = info[@"user_id"];
    
        // unbox name and user_id if necessary
    }