# How best to keep track of an unknown number of objects?

I have a manager class that will manage an unknown number of objects. I'm currently storing the objects in a NSMutableArray object, and when I need to find one, I iterate through the array comparing pointers.

For example, I have an array called managedObjects. I get a delegate method call:

- (void)someDelegateMethod:sender withResults:results {
for (NSDictionary *managedObjectDict in managedObjects) {
if (sender == [managedObjectDict objectForKey:@"DelegatedObject"]) {
NSLog(@"%@",[managedObjectDict objectForKey:@"Value"]);
break;
}
}
}


Now, Objective-C forin loops are handled in batches and are extremely fast... but if I were managing thousands of objects, this could potentially take a bit of time to find the right one.

How can I improve this efficiency?

-

A linear scan for a unique value immediately screams to me that managedObjects should be an NSDictionary with NSValue wrappers around Sender*s as the keys.

In other words, when inserting into managedObjects you would do something like [managedObjects setObject:@{@"Value": @"example} forKey:[NSValue valueWithPointer]].

Then, in your delegate method, you could retrieve it with:

- (void)someDelegateMethod:sender withResults:results {
NSString* value = [self.managedObjects objectForKey:[NSValue valueForPointer:sender]][@"Value"]];
}

-

I'm not an Objective-C guy but, I do know that if you used some sort of hash table structure and could define a hashcode for these objects, that you'd be able to pull them out much faster.

You said at times you "need to find one", I would assume you would know enough about it to be able to generate its hashcode and check your table for it in O(1) time.

-