Question

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

Was it helpful?

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
}

OTHER TIPS

Your problem might be that after interface_fun returns, the object pointed to by name has been deallocated.

You should copy name to a local variable, which is then free'd at the end of the block. (automatic if you are using ARC). Something like this:

NSData *data = [NSData dataWithBytes:name length:strlen(name)+1];
dispatch_async(dispatch_get_main_queue(), ^{
  gui_acton_with_name((char*)[data bytes], user_id);
});

If you are using ARC, you can also pass in name as an NSString* or NSData*. In which case the contents will be retained until your block finishes.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top