Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using an object as key for NSDictionary

I have a bunch of Lessons 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 lesson so we have a NSDictionary with the Lesson as key and an NSNumber having the percent of upload status.

This is a problem because after you insert a Lesson you want to later do a lookup on that same Lesson (perhaps in cellForRowAtIndexPath:) 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?

like image 796
William Entriken Avatar asked Jul 17 '12 23:07

William Entriken


People also ask

Can an object be a key in dictionary c#?

The keys in a dictionary can be a reference type, i.e., objects. When an object is used as the key, the virtual methods "GetHashCode()" & "Equals()" can change how the dictionary search for the entries depending on if they are overridden, and how they are overridden.

What is a NSDictionary object?

An object representing a dynamic collection of key-value pairs, for use instead of a Dictionary variable in cases that require reference semantics.

Does NSDictionary retain objects?

An NSDictionary will retain it's objects, and copy it's keys.

How do you convert NSDictionary to NSMutableDictionary?

Use -mutableCopy . NSDictionary *d; NSMutableDictionary *m = [d mutableCopy]; Note that -mutableCopy returns id ( Any in Swift) so you will want to assign / cast to the right type. It creates a shallow copy of the original dictionary.


1 Answers

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];

https://developer.apple.com/library/mac/documentation/Cocoa/Reference/Foundation/Classes/nsvalue_Class/Reference/Reference.html#//apple_ref/occ/clm/NSValue/valueWithNonretainedObject:

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

like image 150
Chris Trahey Avatar answered Sep 30 '22 15:09

Chris Trahey