NSMutableArray和NSMutableDictionary的文字方法和类方法之间的区别 [英] Difference between literals and class methods for NSMutableArray and NSMutableDictionary

查看:126
本文介绍了NSMutableArray和NSMutableDictionary的文字方法和类方法之间的区别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我开始使用OSX/iOS时

When I started with OSX/iOS I used

    NSMutableArray *        a1 = [NSMutableArray arrayWithCapacity:123] ;
    NSMutableDictionary *   d1 = [NSMutableDictionary dictionaryWithCapacity:123] ;

然后我发现了简单"版本

Then I discovered the 'simpler' version

    NSMutableArray *        a2 = [NSMutableArray array] ;
    NSMutableDictionary *   d2 = [NSMutableDictionary dictionary] ;

我现在已移至:

    NSMutableArray *        a3 = [@[] mutableCopy] ;
    NSMutableDictionary *   d3 = [@{} mutableCopy] ;

从功能上讲,它们看起来都是相同的:无论以哪种方式进行初始化,无论其创建方式如何,都可以使用它们. 区别在哪里?

Functionally, they all seem identical: once initialized either way, they can be used regardless of how they were created. Where are the differences?

特别是,我是否应该假设d3/a3在内存预分配(或缺少)方面比d1/a1与d2/a2更相似?

In particular, should I assume that d3/a3 are more similar to d2/a2 than d1/a1 in terms of memory pre-allocation (or lack thereof) ?

还是这只是样式问题?

推荐答案

第一种形式是类工厂方法,当您知道集合最初需要多大或者知道大小将是恒定的但内容可能改变.

Form one is class factory method that is an optimization useful when you know how large a collection initially needs to be or you know the size will be constant but content may change.

形式二是等效于调用new的类工厂方法.这可能与后跟init的alloc相同或不同,但实际上是相同的.

Form two is a class factory method equivalent to calling new. This may or may not be the same as alloc followed by init, but is effectively the same.

形式三与alloc分别隐式地相同,后跟initWithArray:或initWithDictionary:.它很方便,但是会生成一个不需要的不可变实例,该实例在ARC下会被丢弃,丢弃时可能不清楚.

Form three is implicitly the same as alloc followed by initWithArray: or initWithDictionary: respectively. It's convenient but generates an unneeded immutable instance that is discarded under ARC it may not be clear when it is discarded.

如果您不打算在其他地方再次使用不可变实例,则通常使用形式一或形式二.

Use form one or form two generally if you are not going to ever use the immutable instance again elsewhere.

这篇关于NSMutableArray和NSMutableDictionary的文字方法和类方法之间的区别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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