objective-c - 删除 obj-c 中的对象

标签 objective-c ios cocoa-touch cocoa

我必须如何删除对象? 例如,我有 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/

相关文章:

ios - UITableView 和 UITableViewHeader 在旋转和调整大小后发生冲突

ios - 如何使用具有自定义初始值设定项的枚举类型值的解码结构中的值?

ios - 将 PNG 附加到 MFMailComposer 时,图像会自动旋转为横向

ios - 将按钮添加到 UIPickerView 以转到下一个数字

objective-c - 我如何从 viewWillTransitionToSize 获取有关 View Controller 在旋转后的外观的详细信息?

ios - 删除邮件应用程序时从 iOS 10 上的应用程序发送电子邮件的替代方法?

objective-c - 如何在 NSTableView 中显示行数

ios - CFUUID - 创建一次并在应用程序的整个生命周期中使用

iphone - iPhone 上的 Flash(或 Silverlight)

objective-c - 观察 UITableViewController 的编辑属性