On Tue, Jan 19, 2010 at 11:24 AM, Jens Alfke <j...@mooseyard.com> wrote:
>
> On Jan 19, 2010, at 8:53 AM, Shawn Rutledge wrote:
>
>> I wish NSDictionary (NSMutableDictionary actually) could handle
>> arbitrary mappings of one type of object to another, without copying
>> the keys.
>
> It can. If you have a custom class you want to be able to use as a
> dictionary key without copying, then make it implement the NSCopying
> protocol and add this method:
>        - (id) copyWithZone: (NSZone*)zone {
>                return [self retain];
>        }
> This enables -copy but turns it into a no-op that returns the original
> object. (This is perfectly kosher. Most immutable Foundation objects do the
> same thing, i.e. copying an immutable NSString returns the same object.)

OK thanks, that's good to know.  However in this case I wanted to add
NSSwitch objects to the dictionary.  So it would have to be a subclass
then I guess.

> Of course you also have to implement -hash and -isEqual: to make your class
> play nicely with dictionaries. Make sure these have immutable semantics: if
> the values returned by these can ever change, you'll screw up any dictionary
> or set the object is in.
>
>> I didn't try CFDictionary yet; is that appropriate for an iPhone app?
>
> Yes, you can use CF. Remember that a CFXXXRef is the same as an NSXXX*, you
> can just typecast between them. If you create a CFDictionary you'll have to
> define your own callbacks, and make the copy callback just retain the
> object.
>
> But try NSMapTable first. It's sort of halfway between the two — it's an
> Objective-C class but it has greater flexibility in what it can store and
> how it stores it.

Oh that looks good too, thanks again, I will try it.

I forgot to mention, another problem I ran into was that my dictionary
is a member variable of my UIViewController, I inited it in
initWithNibName, then later when I go to use it in another member
function, I found that it had been garbage-collected.  I used other
member variables the same way, but only the dictionary got
garbage-collected.  So I fixed it by doing [myDict retain]; in the
initWithNibName, but didn't understand why such a thing should be
necessary.
_______________________________________________

Cocoa-dev mailing list (Cocoa-dev@lists.apple.com)

Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com

Help/Unsubscribe/Update your Subscription:
http://lists.apple.com/mailman/options/cocoa-dev/archive%40mail-archive.com

This email sent to arch...@mail-archive.com

Reply via email to