alloc+initWithString: 与 copy 相同吗?
基本上,问题是 - 以下内容本质上是相同的吗?
NSString *value1 = ...;
NSString *value2 = [[NSString alloc] initWithString:value1];
和
NSString *value1 = ...;
NSString *value2 = [value1 copy];
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];
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
从概念上讲,是的。但是,有一个区别:
alloc
始终创建一个新字符串,而copy
可能返回相同的字符串。特别是,不可变对象(例如不可变字符串)可能会通过返回自身而不是创建并返回副本来响应复制。 (毕竟,如果您无法更改原始内容的任何内容,为什么您真的需要副本?)可变字符串将通过创建并返回副本来响应它,正如您所期望的那样。
initWithString:
位于中间:它可能会释放接收器并返回您给它的字符串,类似于copy
返回接收器的方式。但是,如果发生这种情况,则意味着您浪费了使用alloc
创建的字符串的创建时间。使用copy
,您可能根本不需要创建任何其他对象。使用
alloc
和initWithString:
的唯一原因是,如果您有自己的 NSString 子类,并且想要从现有字符串创建它的实例。copy
不会使用您想要的子类。由于在 Cocoa 中几乎从不保证子类化 NSString,因此使用initWithString:
(或stringWithString:
)也是如此。所以底线是,只需使用
copy
(或mutableCopy
)。它更短,更清楚地表达您的意图,并且可以更快。Conceptually, yes. However, there is one difference:
alloc
always creates a new string, whereascopy
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 howcopy
may return the receiver. However, if that happens, it means you wasted the creation of the string you created withalloc
. Withcopy
, you may not need to create any additional objects at all.About the only reason to use
alloc
andinitWithString:
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 usinginitWithString:
(orstringWithString:
).So the bottom line is, just use
copy
(ormutableCopy
). It's shorter, clearer about your intent, and can be faster.与普通对象相比,不可变字符串的处理有点特殊,所以在这种情况下,是的,这两个操作是相同的。
也就是说:
这给了我以下输出:
由于指针地址相同,所以我们正在谈论同一个对象。
Non-mutable strings are treated a bit special, compared to ordinary objects, so in this case, yes, the two operations are the same.
To wit:
Which gives me the following output:
Since the pointer addresses are the same, we are talking about the same object.