Full Decent Full Decent - 1 year ago 88
iOS Question

Using an object as key for NSDictionary

I have a bunch of

s and the class works great. There is a view controller that works with these lessons. This controller needs to know the upload status of a
so we have a NSDictionary with the
as key and an
having the percent of upload status.

This is a problem because after you insert a
you want to later do a lookup on that same
(perhaps in
) to get the progress. This does not work because keys are copied in NSDictionary.

Is it good form to save and fetch keys with something like this:

NSNumber *key = [NSNumber numberWithUnsignedInt:[obj hash]];
[dict setObject:@"... upload progress" forKey:key];

Or there a better approach?

Answer Source

I have used this technique many times in the past, and have had great success by wrapping the key-objects into an NSValue:

NSValue *myKey = [NSValue valueWithNonretainedObject:anInstance];
id anItem =[myDict objectForKey:myKey];


(forgive the formatting; I'm on iPhone. I'll format later :-)

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download