是alloc + initWithString:和copy一样吗? [英] Is alloc+initWithString: same as copy?

查看:125
本文介绍了是alloc + initWithString:和copy一样吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,问题是 - 基本上是一样的吗?

  NSString * value1 = ...; 
NSString * value2 = [[NSString alloc] initWithString:value1];

  NSString * value1 = ...; 
NSString * value2 = [value1 copy];


解决方案

然而,有一个区别: alloc 总是创建一个新的字符串,而 copy 可能返回相同的字符串。 p>

特别地,不可变对象(例如不可变字符串)可能通过返回自己而不是创建和返回来响应 copy 复印件。 (毕竟,如果你不能改变原来的东西,为什么你真的需要一个副本?)可变字符串将回应它创建和返回一个副本,如你所期望的。



initWithString:在中间:它可以释放接收者并返回你给它的字符串,类似于 copy 可能会返回接收者。但是,如果发生这种情况,则意味着您浪费了使用 alloc 创建的字符串的创建。使用 copy ,您可能不需要创建任何其他对象。



关于使用 alloc initWithString:是如果你有你自己的NSString的子类,并想从现有的字符串。 copy 不会使用您想要的子类。因为子类化NSString实际上从不保证在Cocoa,使用 initWithString:(或 stringWithString:)也是如此。



所以底线是,只需使用 copy (或 mutableCopy )。它更短,更清楚你的意图,并可以更快。


Basically, the question is - are the following essentially the same?

NSString *value1 = ...;
NSString *value2 = [[NSString alloc] initWithString:value1];

and

NSString *value1 = ...;
NSString *value2 = [value1 copy];

解决方案

Conceptually, yes. However, there is one difference: alloc always creates a new string, whereas copy may return the same string.

In particular, immutable objects, such as immutable strings, are likely respond to copy by returning themselves rather than creating and returning a copy. (After all, if you can't change anything about the original, why would you really need a copy?) Mutable strings will respond to it by creating and returning a copy, as you'd expect.

initWithString: is in the middle: It may release the receiver and return the string you gave it, similar to how copy may return the receiver. However, if that happens, it means you wasted the creation of the string you created with alloc. With copy, you may not need to create any additional objects at all.

About the only reason to use alloc and initWithString: is if you have your own subclass of NSString and want to make an instance of it from an existing string. copy won't use your desired subclass. Since subclassing NSString is practically never warranted in Cocoa, the same is true of using initWithString: (or stringWithString:).

So the bottom line is, just use copy (or mutableCopy). It's shorter, clearer about your intent, and can be faster.

这篇关于是alloc + initWithString:和copy一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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