Search code examples
iphoneiossynchronizeddidselectrowatindexpathuitableview

Synchronized access to UITableViewDelegate logic


I'd like to ask a question about table view and @synchronized contruct. I have to execute the code inside didSelectRowAtIndexPath once, even if user keep tapping on table cell...

I have a table used as menu in a game. I'd like to provide synchronized access to the logic implemented in didSelectRowAtIndexPath.

I worte the following code:

//condition = YES in init code

    - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
    {
        @synchronized( self)
        {
            if( !condition)
            {
                NSLog(@"multiple execution is not allowed...");
                return;
            }
            condition = NO;
            ...
            //code
            ...
        }
    }

I tested it on my ipone 3gs with ios 4.3.4 and worked (i made tests and the behaviour is as expected) but my client tested it on his 3g with ios 3.x installed and it seems not to work.

I thought at using GCD (by enclosing code in dispatch_once()), but it's supported starting from ios 4.x.

Have you any insight on why @synchronized doesn't work on my client's phone?

Thanks!


Solution

  • @synchronized should not be not needed here.

    • you can expect the delegate call to be made from the main thread (assuming you do not call it).
    • dispatch_once seems like an unusual choice here. if you are sure it is good, try pthread_once for iOS 3. it's odd because it operates using mutable global state. IOW, "I only ever want to make one table".
    • testing a BOOL is fast.

    My guess? Your table is being removed (view unloading) and may fail to be recreated on reload.