具有NSMutableDictionary(Objective-C)的对象键 [英] Object keys with NSMutableDictionary (Objective-C)

查看:146
本文介绍了具有NSMutableDictionary(Objective-C)的对象键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想存储一堆键值对,键是从NSObject继承的我自己的对象(ObjectA),而值是一个整数.
我正在尝试使用NSMutableDictionary.我知道您只能在字典中存储对象类型,所以我有以下内容:

I want to store a bunch of key value pairs, with the key being my own object (ObjectA) that inherits from NSObject, and the value being an int.
I am trying to use an NSMutableDictionary. I understand that you can only store object types in the dictionary, so I have the following:

id value = [NSNumber numberWithInt:my_number];

[[self dictionary] setObject:value forKey:myObjectA];

现在这让我出错了,说

-[ObjectA copyWithZone:]:无法识别的选择器已发送到实例

-[ObjectA copyWithZone:]: unrecognized selector sent to instance

这很好,我知道对象密钥需要实现NSCopying协议.但是我随后读到,您可以通过使用NSValue包装对象来实现此目的.

which is fine, I understand that object keys need to implement the NSCopying protocol. However I then read that you can do this by wrapping your objects using NSValue.

有人可以解释一下我将如何包装我的对象,然后又如何才能通过键找到值吗?我仍然可以使用dictionary objectForKey:myObjectA还是在搜索时还必须用NSValue对象包装myObjectA?还是应该在自定义类上实现NSCopying,或者改用字符串键?

Can someone please explain how I would wrap my objects, and how I can then find the value by the key? Am I still able to use dictionary objectForKey:myObjectA or do I have to wrap myObjectA with an NSValue object while I'm searching as well? Or should I be implementing NSCopying on my custom class, or using a string key instead?

我正在寻找使用字典的最简单,最简单的方法,如果必须的话,我将实现一个字符串键并使用setValue:forKey:,但我宁愿使用对象键.

I am looking for this simplest and easiest way to use a dictionary, if I have to I'll implement a string key and use setValue:forKey: instead but I'd rather use the object key if I can.

推荐答案

始终会复制字典键.因此,您只需要实现

Dictionary keys are always copied. So you simply need to implement the NSCopying protocol for your class, which is just the copyWithZone: method.

此外,您还应该为您的课程实施isEqual:方法.

Additionally you should implement the isEqual: method for your class.

如何实现copyWithZone:取决于许多因素(主要因素:深层副本与浅层副本).参见Apple的实施对象复制指南和此SO答案.

How to implement your copyWithZone: depends on a number of factors (main factor: deep vs. shallow copy). See Apple's Implementing Object Copy guide and this SO answer.

这篇关于具有NSMutableDictionary(Objective-C)的对象键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆