建议初始化数组(或其他对象)的最佳方法 [英] Suggest the best way of initialization of array ( or other objects )

查看:98
本文介绍了建议初始化数组(或其他对象)的最佳方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对以下两种初始化方式感到有点困惑.....

I am a bit confused in the following two ways of initialisations.....

方式1:

- (void) myMethod{

    NSArray *myArray = [[NSArray alloc] initWithObjects:obj1,obj1,nil];
    [self setClassArray:myArray];
    [myArray release];
}

方式2:

- (void) myMethod{

NSArray *myArray = [NSArray arrayWithObjects:obj1,obj2,nil];
[self setClassArray:myArray];
}

在方法1中,我使用了一个alloc init方法,这是一个实例方法因为我已经使用了一个alloc语句,所以我必须自己释放数组。

In way 1, I have used a alloc init method which is a instance method and as I have used an alloc statement I have to release the array myself.

在方式2中,我使用静态方法来初始化数组,因为没有使用的alloc语句我不需要释放系统将处理的内存。

In way 2, I have used a static method to initialze the array and as there is no alloc statement used I dont need to release the memory the system will take care of that.

方式1,耗时并且如果不小心可能导致内存泄漏

Way 1, is time consuming and can to lead to memory leaks if not taken care

方式2,写作速度更快,你不需要处理内存泄漏

Way 2, is faster in writing and you dont need to take care of memory leaks

但是,仍然我已经看到标准源代码中使用的way1比way2更常见。我不知道为什么人们会这样做,或者我在某个地方做错了。

But , still i have seen the way1 used in standard source codes more often than the way2. I have no idea why people do this or if I am wrong at some place.

答案和评论都是特别邀请。请建议最好的编程实践。

Answers and comments are oppenly invited. Please suggest the best programming practice.

推荐答案

您的第二个示例使用了一个便利构造函数,它返回一个自动释放的对象。那么问题是,使用 autorelease alloc / release是否更好 mmalc 答案解释了自动释放对象的缺点。 (基本上,尽可能使用 alloc / release 。)

Your second example uses a convenience constructor, which returns an autoreleased object. The question, then, is whether it's better to use autorelease or alloc/release. mmalc's answer on this StackOverflow thread explains the drawbacks of autoreleasing objects. (Basically, use alloc/release whenever possible.)

另外(这可能说明显了),有些类可能没有方便构造函数,所以在使用这些时你必须使用 alloc / 发布

Also (this may be stating the obvious), some classes might not have convenience constructors, so when working with these you'd have to use alloc/release.

这篇关于建议初始化数组(或其他对象)的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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