Cocoa 内存管理 NSArray 与对象

标签 cocoa memory-management

我在释放对象时遇到问题。为了更好地解释它,我在下面包含了我的代码。

NSTask *task = [NSTask new];
NSTask *grep = [NSTask new]; 
NSPipe *pipe = [NSPipe new];

[task setStandardError: pipe];
[grep setStandardInput: pipe];
[pipe release];
pipe = [NSPipe new];
[grep setStandardOutput: pipe];

[task launch];
[grep launch];

NSString *string = [[[[[[NSString alloc] initWithData: [[[grep standardOutput] fileHandleForReading] readDataToEndOfFile] encoding: NSASCIIStringEncoding] autorelease] componentsSeparatedByString: @" "] objectAtIndex: 3] substringToIndex: 8];

NSMutableDictionary *dict = [NSMutableDictionary new];
[dict setObject: string forKey: @"myKey"];
[records addObject: dict];
[dict release];

[task release];
[grep release];
[pipe release];

我如何释放字符串以及是否有其他泄漏?另外,如果我使用 removeAllObjects 从数组 records 中删除所有内容,那么所有内容都可以释放吗?该数组不应该被释放并且始终可用,我只是担心它的对象。

编辑:指出的唯一泄漏与 NSPipe 有关,应该在代码中修复。

感谢您的帮助!

最佳答案

Objective-C 中的内存管理有一个 fundamental rule :

You take ownership of an object if you create it using a method whose name begins with “alloc” or “new” or contains “copy” (for example, alloc, newObject, or mutableCopy), or if you send it a retain message. You are responsible for relinquishing ownership of objects you own using release or autorelease. Any other time you receive an object, you must not release it.

因此,代码示例中对 new 的每次调用都应与对 releaseautorelease 的调用相平衡。 NSArray 以及代码中的大多数其他对象都不是用其中任何一个创建的,因此不需要释放它。 [NSString alloc] 是自动释放的,所以它会被处理。集合管理自己的项目,根据需要保留和释放它们:插入项目时,它会被保留;当它被移除时,它就被释放了。字典键被复制而不是保留。

您创建的第一个 NSPipe 是不平衡的 new(因此发生泄漏)。在为 grep 的标准输出创建管道之前释放它。也许您只是将其排除在示例之外,但您也没有为 grep 任务设置任何参数。

关于Cocoa 内存管理 NSArray 与对象,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2411520/

相关文章:

objective-c - Xcode 4 添加动态库

cocoa - 如何使用NSWindowController?

java - 对象之间是否可以通过相互引用使彼此“不可删除”?

c++ - STL分配器复制构造函数要求的目的是什么

ios - 让推送像现在一样生动

objective-c - 当 NSTokenField 成为第一响应者时,如何执行操作(显示弹出窗口)?

objective-c - 使用 *.nib 文件显示模式窗口

c++ - 我必须删除 C++ 中的静态数组吗?

c# - CUDA 设备中的内存分配不是预期的

c++ - 关于 Armadillo 稀疏矩阵中的内存分配