我有一个由NSMutableStrings为其键和对象填充的NSDictionary对象。 我已经能够通过使用setString:方法更改原始NSMutableString来更改密钥。 然而,不管最初用于设置密钥的字符串的内容如何,它们的密钥都保持不变。
我的问题是,被保护的关键是否被改变,意味着它将永远是相同的,除非我将它删除并添加到字典中?
谢谢。
I have an NSDictionary object that is populated by NSMutableStrings 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?
Thanks.
最满意答案
当项目被设置时,键是-copy ,所以你以后不能改变它是没有用的。
为词典添加条目的方法 - 无论是作为初始化(对所有字典)还是修改(对于可变词典)的一部分 - 拷贝每个关键参数(键必须符合NSCopying协议)并将副本添加到字典中。 每个对应的值对象都会收到一个保留消息,以确保它在字典完成之前不会被释放。
您可以使用CFDictionary与kCFTypeDictionaryKeyCallBacks,或者只是替换该项目:
id value = [dictionary objectWithKey:oldKey]; [dictionary setObject:value withKey:newKey]; [dictionary removeObjectForKey:oldKey];The keys are -copy'd when the items are set, so you can't changing it afterwards is useless.
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.
You could use CFDictionary with kCFTypeDictionaryKeyCallBacks, or just replace the item:
id value = [dictionary objectWithKey:oldKey]; [dictionary setObject:value withKey:newKey]; [dictionary removeObjectForKey:oldKey];更多推荐
发布评论