我必须如何删除对象? 例如,我有 NSDictionary 和其中的一些 NSStrings:
NSDictionary *dict = [NSDictionary dictionaryWithObjects....];
NSString *str = [dict objectForKey:@"key"];
[str release];
或 [str dealloc];
或 str = nil
或者它是自动释放对象?
如果我将删除 not autorelease dict,所有子项也会被删除吗?
最佳答案
Memory management在 objective c 中是基于对象所有权的。如果您拥有该对象,则必须释放该对象。
Cocoa 制定了以下政策:
You own any object you create
You create an object using a method whose name begins with “alloc”, “new”, “copy”, or “mutableCopy” (for example, alloc, newObject, or mutableCopy).You can take ownership of an object using retain.
When you no longer need it, you must relinquish ownership of an object you own
You relinquish ownership of an object by sending it a release message or an autorelease message.You must not relinquish ownership of an object you do not own
这只是之前明确规定的政策规则的必然结果。
在你的情况下
NSDictionary *dict = [NSDictionary dictionaryWithObjects....];
NSString *str = [dict objectForKey:@"key"];
您不是 str 的所有者,因此您不应该释放该对象。
关于objective-c - 删除 obj-c 中的对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9348245/