views:

79

answers:

1

I am implementing a class that has to store arbitrary objects together with a string. i.e.

myUIViewObject, @"that's a nice view"
myUIViewController, @"not really special"
myOtherObject, @"very important one"

this list can be extended and modified at any time, so I thought about using NSMutableDictionary here. But I am not really sure...

The object should be the key, i.e. I want to find easily the matching string for myUIViewController or myOtherObject when I ask for it like so:

- (NSString*)checkObjNoteStringForObject:(id)anyObjectInList;

The other problem is, that when an object gets added to that "list", I don't want it to be retained because of that. NSMutableDictionary retains it's contents, right? Could I just send a -release afterwards to undo this unwanted behaviour, and when removing from the list just sending -retain before doing so? Or is there a more elegant way?

What do you suggest? Thanks @ all!

+1  A: 

If your dictionary key is not retained, once it is deallocated accesses to the dictionary will lead to undefined behaviour (in practice, they'll crash if a lookup happens to hit that dictionary element). To do what you want, you need a strategy to remove the objects from the dictionary when necessary.

If you do have one – for instance, overriding the objects’ -dealloc and removing them from there – you can do what you want using +[NSValue valueWithNonretainedObject:]. The NSValue will refer to your object without retaining it, and the dictionary will copy the NSValue (keys are copied, not retained). Just remember to create an NSValue for each time you want to look something up in the dictionary; a helper function or method is a good idea.

Ahruman
When the key, in this case an NSValue, is copied: Does that mean that the object referenced by the NSValue is not copied too? It would be bad if the objects get copied, because some of them may have large memory footprints.
HelloMoon
No. NSValue is just a “bag of bits” with type information attached, so a true copy would just copy the pointer to your object. Since NSValue is immutable, its implementation of -copy will just call -retain. The distinction would be important if you were using your own objects as keys, though; they’d need to implement the NSCopying protocol.
Ahruman