Question

I have some code that takes an NSString as input and uses that string to create an object. I need to make sure that it does not operate on the same string twice, e.g. if called from different threads, or even if the same thread tries to do it recursively.

I can make a start by making a dictionary of my initialized objects and grabbing that object if passed the same string again. But this still leaves the problem of what happens when the object is requested a second time while other code is initializing it.

I see that Apple has provided me with the NSLock class. I am at a loss as to how to apply it to my problem. I see Apple lets me name my locks, but I don't see any way to access the lock with a given name. I suppose I could make a dictionary of locks, but even that does not seem bulletproof -- what if two threads try to make the lock of the same name at the same time?

Can anyone point me in the right direction here?

Was it helpful?

Solution

What about making a static NSMutableArray with all your strings and synchronize your code.

Of course you need to initialize the array somewhere first ;)

Maybe like this:

static NSMutableArray* myArrayWithStrings;

-(void) someMethod:(NSString*) key
{
    @synchronized(myArrayWithStrings)
    {
        if(![myArrayWithStrings containsObject:key])
        {
            NSLog(@"Working with the key %@", key);
            [myArrayWithStrings addObject:key];

        }else
        {
            NSLog(@"Ignoring key '%@'. Already worked with it.",key);
        }
    } 
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top