How thread-safe is my unique code?

I have a small class of values ​​that I create many instances of. Often with the same meaning. This class is used as a kind of identifier, so the main use is to compare instances of this class with each other (via isEqual:).

To save some comparison of memory and time, I save only unique instances in NSHashTableand use pointer comparison instead isEqual:.

So my designated initializer looks like this:

- initWithStuff: (NSString *)stuff;
{
    self = [super init];
    if (!self) return nil;

    // ... (actual initialisation code omitted)

   hash = UniquingHashTable();

   static OSSpinLock spinlock = OS_SPINLOCK_INIT;
   OSSpinLockLock( &spinlock );

   id member = [hash member: self];
   if (member) self = member;
   else [hash addObject: self];

   OSSpinLockUnlock( &spinlock );

   return self;
}

UniquingHashTable() NSHashTable [NSHashTable weakObjectsHashTable], . weakObjectsHashTable - , , . dispatch_once.

, , . , . , ( ), - isEqual:?

, :

MyClass *a = [[MyClass alloc] initWithStuff: stringA];
MyClass *b = [[MyClass alloc] initWithStuff: stringB];

[a isEqual: b] == [stringA isEqual: stringB];

.

, ,

[a isEqual: b] == (a == b)

isEqual: . (, , ).

NSMutableSet NSHashTable, . , - , ,

[a isEqual: b] && (a != b)

.

+5
1

, . / .

, uniquing [ factory] stuff. , , , stuff . , alloc/dealloc [].

, UniquingHashTable(), static dispatch_once() initWithStuff: ( factory). ( - ).

GCD ; user- > kernel, .

- hash isEqual:, ( , ... - , isEqual: ). , - . , , isEqual: ( , ).


isEqual: , , , , .

isEqual:, .

( ) malloc free ( +alloc -dealloc) . , -, isEqual: ( - ).

isEqual: ?

+4

All Articles