我可以更改NSDictionary的密钥吗? [英] Can I change an NSDictionary's key?

查看:53
本文介绍了我可以更改NSDictionary的密钥吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个NSDictionary对象,该对象由NSMutableString实例填充其键和对象.我已经能够通过使用setString:方法更改原始的NSMutableString来更改密钥.但是,无论最初用于设置密钥的字符串内容如何,​​它们的密钥都保持不变.

I have an NSDictionary object that is populated by instances of NSMutableString for its keys and objects. I have been able to change the key by changing the original NSMutableString with the setString: method. They key however remains the same regardless of the contents of the string used to set the key initially.

我的问题是,是否可以防止更改密钥,这意味着除非我将其删除并在字典中添加另一个密钥,否则密钥将始终是相同的?

My question is, is the key protected from being changed meaning it will always be the same unless I remove it and add another to the dictionary?

谢谢.

推荐答案

设置项目时,键是-copy键,因此以后再进行更改都是无用的.

The keys are -copy'd when the items are set, so you can't changing it afterwards is useless.

将条目添加到字典的方法(无论是作为初始化的一部分(对于所有字典)还是在修改过程中(对于可变字典)-复制每个键参数(键必须符合NSCopying协议)并将副本添加到字典.每个对应的值对象都会收到一条保留消息,以确保在字典通过它之前不会被释放.

Methods that add entries to dictionaries—whether as part of initialization (for all dictionaries) or during modification (for mutable dictionaries)—copy each key argument (keys must conform to the NSCopying protocol) and add the copies to the dictionary. Each corresponding value object receives a retain message to ensure that it won’t be deallocated before the dictionary is through with it.

您可以将CFDictionary与kCFTypeDictionaryKeyCallBacks一起使用,或仅替换以下项目:

You could use CFDictionary with kCFTypeDictionaryKeyCallBacks, or just replace the item:

id value = [dictionary objectWithKey:oldKey];
[dictionary setObject:value withKey:newKey];
[dictionary removeObjectForKey:oldKey];

这篇关于我可以更改NSDictionary的密钥吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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