[[NSMutableDictionary alloc] initWithObjects:...]和[NSMutableDictionary dictionaryWithObjects:...]之间的区别? [英] Difference between [[NSMutableDictionary alloc] initWithObjects:...] and [NSMutableDictionary dictionaryWithObjects:...]?
问题描述
仍在学习Objective-C / iPhone SDK。我想我知道为什么这不工作,但我只想确认。
Still learning Objective-C / iPhone SDK here. I think I know why this wasn't working but I just wanted to confirm.
在 awakeFromNib
使用 [[NSMutableDictionary alloc] initWithObjects:...]
它实际上分配(iPhone)系统内存与此 NSMutableDictionary
data ,但是当我使用 [NSMutableDictionary dictionaryWithObjects:...]
它只能在堆栈中使用吗?
In awakeFromNib
, if I use [[NSMutableDictionary alloc] initWithObjects:...]
it actually allocates (iPhone) system memory with this NSMutableDictionary
data, but when I use [NSMutableDictionary dictionaryWithObjects:...]
it is only available in the stack right?
例如,将来如果我尝试通过IBAction从按钮中访问 myMutableDict
,则 myMutableDict
对象可能已被释放,导致我的应用程序崩溃,即使我已经在我的.h文件中这样定义,并合成:
For example, in the future if I try to access myMutableDict
from a button press via IBAction, the myMutableDict
object may have been freed, causing my app to crash, even though I have defined it like so in my .h file, and synthesized it:
@property (nonatomic, retain) NSMutableDictionary *myMutableDict;
由于某种原因,更改为 [[NSMutableDictionary alloc] initWithObjects:... ] 修正此问题。
For some reason changing to [[NSMutableDictionary alloc] initWithObjects:...]
fixed this.
推荐答案
+ dictionaryWithObjects:
返回自动发布的字典
-initWithObjects:
您必须自己发布
+dictionaryWithObjects:
returns an autoreleased dictionary
-initWithObjects:
you must release yourself
希望字典持久化为一个实例变量,你应该使用init方法创建它或保留一个自动释放的版本,无论哪种方式你应该确保在dealloc方法中释放它
if you want the dictionary to persist as a instance variable, you should create it with an init method or retain an autoreleased version, either way you should be sure to release it in your dealloc method
有关此主题的优秀资源是可可的内存管理编程指南。
An excellent resource on this topic is the Memory Management Programming Guide for Cocoa.
这篇关于[[NSMutableDictionary alloc] initWithObjects:...]和[NSMutableDictionary dictionaryWithObjects:...]之间的区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!