Cocoa Touch - 如何正确地为指针分配新值而导致内存泄漏?

wan*_*ust 0 iphone cocoa-touch pointers memory-leaks

我刚刚完成了我的第一个简单的iPhone应用程序; 我正在使用Instruments来查找内存泄漏.

关于如何重用指针,我有点迷茫.我已经阅读了Apple文档,但我仍然不明白正确的程序.

Apple文档说,"另一个典型的内存泄漏示例发生在开发人员分配内存,将其分配给指针,然后为指针分配不同的值而不释放第一块内存.在此示例中,覆盖地址指针擦除对原始内存块的引用,使其无法释放."

我是否真的必须每次释放并创建一个新指针?

在dateFormatter上创建内存泄漏的示例:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    

// year 
[dateFormatter setDateFormat:@"yyyy"];  
NSInteger year = [[dateFormatter stringFromDate:date] integerValue];    

// month
[dateFormatter setDateFormat:@"MM"];
NSInteger month = [[dateFormatter stringFromDate:date] integerValue];
...

[dateFormatter release];
Run Code Online (Sandbox Code Playgroud)

谢谢你的帮助!

Geo*_*lly 7

这个例子中没有内存泄漏.这是100%有效.Apple在文档中的含义是这样的:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy"];
NSInteger year = [[dateFormatter stringFromDate:date] integerValue];

// new instance of NSDateFormatter without releasing the old one
dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSInteger month = [[dateFormatter stringFromDate:date] integerValue];

[dateFormatter release];
Run Code Online (Sandbox Code Playgroud)

以下是一些防止这些错误的提示:

  1. 重新使用指针时要注意.
  2. 总是使用这个结构:[[[NSDateFormatter alloc] init] autorelease]或者使用像[NSArray arrayWithCapacity:...]这样的容易成员.这在Cocoa中通常是一个好主意,因为开销很小.如果你在iPhone上这更重要.Apple建议手动释放对象以保持低内存.但与往常一样,在优化之前首先进行分析
  3. 不要使用buffer可能重用的广泛变量名称.
  4. 重用变量不会节省内存.编译器自动优化这些事情.