Cocoa Touch问题。应该保留[NSMutableArray数组]吗? [英] Cocoa Touch Question. Should [NSMutableArray array] be retained?

查看:87
本文介绍了Cocoa Touch问题。应该保留[NSMutableArray数组]吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这里是我写的一些代码的要点。我担心我不能正确解决与NSMutableArray上的数组类方法的retain / release问题。以下是否确实会泄漏内存?

Here is the gist of some code I'm writing. I'm concerned that I am not properly addressing the retain/release issues with the array class method on NSMutableArray. Is the following actually leaking memory?

for(a while) { 
    // do stuff
    NSMutableArray *a = nil;
    // do stuff
    if (!a) {
        a = [NSMutableArray array];
    }
} // for(a while)


推荐答案

在这段代码中你不会泄漏内存,并且在运行循环结束时自动释放数组时会自动释放数组将导致崩溃。

You wouldn't leak memory in this code, and releasing the array yourself will cause a crash when the array is autoreleased at the end of the run loop.

大多数Cocoa类提供了几种方法来创建一个新对象,并且非常符合这个约定:

Most Cocoa classes provide a couple of ways of making a new object, and are very consistent with this convention:


  1. [[NSSomeObject alloc] init] :您负责释放对象(实例方法)。

  1. [[NSSomeObject alloc] init] : you are responsible for releasing the object (instance method).

[NSSomeObject someObject] :对象将被自动释放,通常在运行循环结束时(类方法)。它大致相当于 [[[NSSomeObject alloc] init] autorelease]

[NSSomeObject someObject] : the object will be autoreleased for you, usually at the end of the run loop (class method). It's roughly equivalent to [[[NSSomeObject alloc] init] autorelease].

实例方法的正确使用是:

The proper use of the instance method would be:

a = [[NSMutableArray alloc] init];
// do stuff
[a release];

正确使用类方法是:

a = [NSMutableArray array];
// do stuff, array is in the autorelease pool

注意,Apple已经推荐你远离便利方法尽可能提高性能。这是有争议的建议,可能无法节省处理器时间,并且分离alloc-init从一个对象的发布,你可能不会真正关心保持。

Note that Apple has recommended you stay away from the convenience methods as much as possible to improve performance. This is controversial advice, may not save much processor time, and separates the alloc-init from the release on an object you may not actually care much about keeping.

这篇关于Cocoa Touch问题。应该保留[NSMutableArray数组]吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆