快速发布
如何简洁地处理这种情况。我没有在 if
语句中正确释放 contactDictionary
...
NSNumber *pIDAsNumber;
...
NSMutableDictionary *contactDictionary = [NSMutableDictionary dictionaryWithDictionary:[defaults dictionaryForKey:kContactDictionary]];
if (!contactDictionary) {
contactDictionary = [[NSMutableDictionary alloc] initWithCapacity:1];
}
[contactDictionary setObject:pIDAsNumber forKey:[myClass.personIDAsNumber stringValue]];
[defaults setObject:contactDictionary forKey:kContactDictionary];
How to succinctly handle this situation. I'm not properly releasing contactDictionary
in the if
statement...
NSNumber *pIDAsNumber;
...
NSMutableDictionary *contactDictionary = [NSMutableDictionary dictionaryWithDictionary:[defaults dictionaryForKey:kContactDictionary]];
if (!contactDictionary) {
contactDictionary = [[NSMutableDictionary alloc] initWithCapacity:1];
}
[contactDictionary setObject:pIDAsNumber forKey:[myClass.personIDAsNumber stringValue]];
[defaults setObject:contactDictionary forKey:kContactDictionary];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
通常,使用
[NSMutableDictionary DictionaryWithCapacity:1]
而不是 alloc/init。这将为您提供一个自动释放的字典,从内存管理的角度来看,其行为与上面的字典相同。但是......在这种特定情况下,您的 if 子句永远不会为真(除非您耗尽内存,在这种情况下您会遇到更大的问题)。
-dictionaryWithDictionary:
如果传递 nil,则返回一个空字典而不是 nil。因此,即使-dictionaryForKey:
返回 nil,-dictionaryWithDictionary:
仍然会创建一个空的可变字典供您添加。Normally, use
[NSMutableDictionary dictionaryWithCapacity:1]
instead of alloc/init. That will give you an autoreleased dictionary that will, from a memory management perspective, behave identically to the one above. However...In this specific case, your if clause will never be true (unless you run out of memory, in which case you have bigger problems).
-dictionaryWithDictionary:
returns an empty dictionary rather than nil if it is passed nil. So, even if-dictionaryForKey:
returns nil,-dictionaryWithDictionary:
will still create an empty mutable dictionary for you to add to.您可以完全删除
if
语句,因为-[NSMutableDictionarydictionaryWithDictionary:]
始终返回一个字典。另外,不要使用
[NSMutableDictionarydictionaryWithCapacity:1]
来获取空的、自动释放的可变字典。只需使用[NSMutableDictionary 字典]
。You can drop the
if
statement entirely, because-[NSMutableDictionary dictionaryWithDictionary:]
always returns a dictionary.Also, don't use
[NSMutableDictionary dictionaryWithCapacity:1]
to get an empty, autoreleased mutable dictionary. Just use[NSMutableDictionary dictionary]
.