NSString保留复制问题

发布于 2024-08-22 03:40:53 字数 276 浏览 8 评论 0原文

我在这里看到了一些关于使用保留或复制字符串问题的帖子。我仍然无法完全理解其中的差异或重要性。

就我而言,目前我有一个类,其中包含大量 nsstring 来保存字符串。

我希望此类仅实例化一次,并且希望其 nsstring 变量根据表视图中单击的索引进行更改。

我是否正确地说,如果我选择使用保留,每次我在表视图单击上设置它们的值时,我的 nsstrings 都会被覆盖,并且如果我选择复制,我会以某种方式拥有每个字符串的 2 个实例....?

对不起......我完全不明白

I've seen a few posts on here about the issue of using retain or copy for strings. I still can't quite get my head around the difference or the importance.

In my case at the moment I have a class with a whole load of nsstrings to hold strings.

I want this class to only be instantiated once and I want its nsstring variables to change depending on the index clicked in a table view.

Would I be correct in saying that if I chose to use retain that my nsstrings would be overwritten each time I set their value on my tableview click and that if I chose copy I would somehow have 2 instances of each string....?

I'm sorry ..... I totally don't get it

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

圈圈圆圆圈圈 2024-08-29 03:40:53

这是一个关于复制可变对象与不可变对象的问题。由于 NSString 对象是不可变的(你不能改变它们的内容),它们实现 -copy 是这样的:

- (id) copyWithZone: (NSZone *) zone
{
    return [self retain];
}

如果你仔细想想,没有理由复制一个不可变的对象,因为那是浪费内存。另一方面,NSMutableString 对象可以在其生命周期内看到其内容发生变化,因此如果您请求 NSMutableString 的副本,您将获得一个真实的副本,一个不同的对象。

如果你的字符串不是 NSMutableStrings,那么保留或复制它们并不重要。但是,如果您稍后重构代码以使用 NSMutableStrings,那么选择正确的方法非常重要。一个常见的逻辑应该为你回答以下问题:如果我得到一个对象,其内容可能会在外部发生变化,我需要哪个值?通常您会想要复印一份。

This is a question about copying mutable objects vs. immutable ones. Since NSString objects are immutable (you cannot change their contents), they implement -copy like this:

- (id) copyWithZone: (NSZone *) zone
{
    return [self retain];
}

If you think about it, there's no reason to duplicate an immutable object because that's a waste of memory. On the other hand, NSMutableString objects can see their contents change during their lifetime, so if you request a copy of an NSMutableString, you will get a real copy, a different object.

If your strings are not NSMutableStrings, it does not matter whether you retain or copy them. However, choosing the right method is important if you later refactor your code to use NSMutableStrings. A common logic should answer the following question for you: if I get an object whose contents may change outside, which value do I need? More often than not you will want to make a copy.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文