objective-C:关于复制/保留NSString的简单问题 [英] objective-C: simple question about copy/retain NSString

查看:95
本文介绍了objective-C:关于复制/保留NSString的简单问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我将NSString设置为属性

If I set a NSString as property

@property (copy) NSString* name;

我总是想使用(复制),这样如果它的值发生变化,所有带有这种字符串的对象仍然具有旧值(如此处所述)。

I always want to use (copy), so that if its value change, all object with such string still have the old value (as specifiedhere).

但是,如果我的NSString不是类属性会发生什么,但它只是在代码中声明了?在每次分配新值时是保留还是复制?

However, what happens if my NSString is not a class property, but it is just declared in the code ? Is in that case retained or copied everytime I assign a new value ?

谢谢

推荐答案

这取决于你如何声明它。你应该阅读文档。基本上规则是:

It depends on how you declare it. You should read the documentation on memory management. Basically the rules are:

NSString *aString = [NSString stringWithString:@"Hello"];
NSString *bString = [NSString stringWithFormat:@"%@", @"Hello"];

在这些情况下,不会复制或保留字符串。它是自动释放的,这意味着它将在下次自动释放池耗尽时自动解除分配。您不必在它们上调用release方法。 (因此,分配新值不会导致泄漏。)

In these cases, the string is not copied or retained. It is autoreleased, which means it will be automatically deallocated the next time the autorelease pool drains. You do not have to call the release method on them. (So assigning a new value will not cause it to leak.)

NSString *cString = [[NSString alloc] initWithFormat:@"%@", @"Hello"];
[cString release];

根据Objective C约定,使用alloc并保留计数为1的方法不会自动释放,所以你需要明确地释放它们。分配新值而不释放旧值将导致泄漏。

According to Objective C convention, methods that use alloc and have a retain count of one are not autoreleased, so you need to release them explicitly. Assigning a new value without releasing the old one will cause a leak.

您还可以在字符串上显式调用复制方法或保留方法。在任何一种情况下,新字符串的保留计数为1并且不会自动释放,因此在分配新值之前,您需要在其上调用release方法。

You can also explicitly call a "copy" method or a "retain" method on a string. In either case, the new string will have a retain count of 1 and will not be autoreleased, so you will need to call the release method on it before you assign a new value.

NSString *dString = [cString retain];
NSString *eString = [cString copy];

...
[dString release];
[eString release];

如果是属性,并且你使用self.variableName,这将为你照顾(通过使用@synthesize生成的getter和setter)。如果你明确地这样做,你必须确保在你所谓的保留或复制的变量上调用release。

If it is a property, and you use self.variableName, this will be taken care of for you (through the getters and setters which are generated with @synthesize). If you do it explicitly, you must make sure to call release on variables that you have called retain or copy on.

编辑:作为一些下面的评论员已经注意到,在所有权方面考虑管理通常是描述这些想法的首选,而不是保留计数。

As some commentators below have noted, thinking about management in terms of "ownership" is usually the preferred of describing these ideas, rather than retain count.

这篇关于objective-C:关于复制/保留NSString的简单问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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