6
\$\begingroup\$

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?

asked Mar 22, 2014 at 2:39
\$\endgroup\$

2 Answers 2

4
\$\begingroup\$

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"]];
}
answered Mar 22, 2014 at 2:47
\$\endgroup\$
4
\$\begingroup\$

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.

answered Mar 22, 2014 at 2:47
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.