NSString和retainCount问题

发布于 2024-09-13 19:00:19 字数 514 浏览 4 评论 0原文

我在接口部分声明了一个 NSString:

@property(非原子,保留)NSString *filePath;

在 viewDidLoad 中,我给它一个值,当我尝试从我的一个自定义方法调用它时,它第一次起作用,但第二次它就崩溃了。在我看来,filePath 是在第一次调用期间自动释放的。

我尝试了一种不同的方法,在我的方法中我做了这样的事情:

NSString *path = [[[NSString init] alloc] autorelease]; path = [文件路径副本];

这次似乎有效,但是当检查路径的retainCount时,它不断增加。 第一次调用该方法时,retainCount 为 4,但第二次为 2,第三次为 3,依此类推。

好的,我理解 filePath 会因为 [copy] 而增加,但为什么路径变量也会增加? 为什么在第一种情况下它不起作用?

I have a NSString declared in the interface part:

@property (nonatomic, retain) NSString *filePath;

In viewDidLoad I give this a value and when I am trying to call it from one of my custom methods it works for the first time but on the second it crushes. In my opinion filePath was autoreleased during the first call.

I tried a different approach, in my method I have done something like this:

NSString *path = [[[NSString init] alloc] autorelease];
path = [filePath copy];

and this time seems to work, but when checking the retainCount of path it is constantly increasing.
The first time the method is called, retainCount is 4 but for the second is 2, third is 3 and so on.

Ok, I understand for filePath to be increasing, because of [copy] but why also for path variable?
And why in the first case it didn't worked?

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

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

发布评论

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

评论(1

嗳卜坏 2024-09-20 19:00:19

您没有显示所有代码,因此很难得出结论。然而:

NSString *path = [[[NSString init] alloc] autorelease];
path = [filePath copy];

没有意义:首先分配一个 NSString,并让 path 指向它。然后你让path指向其他东西。 NSString 未被使用(但会被自动释放清理)。

我看到您仅通过名称访问 filePath ,而不是通过 getter/setter 。如果您使用 self.filePath ,那么

self.filePath = [NSString stringWithFormat:@"..."]; // or any other string

保留/释放业务将由 setter 正确处理。准确地说,filePath = ...self.filePath = ... 之间的区别在于后者保留您的对象正在分配。

如果您不太有信心知道可可引擎盖下发生了什么,您真的不应该查看保留计数来调试。

You don't show all code so it is hard to say anything conclusive. However:

NSString *path = [[[NSString init] alloc] autorelease];
path = [filePath copy];

makes no sense: first you allocate an NSString, and let path point to it. Then you let path point to something else. The NSString is not used (but will be cleaned up by the autorelease).

I see you access filePath just by its name, not through the getter/setter. If you use self.filePath, like

self.filePath = [NSString stringWithFormat:@"..."]; // or any other string

then the retain/release business is handled properly by the setter. To be precise, the difference between filePath = ... and self.filePath = ... is that the latter will retain the object you are assigning.

You should really not be looking at the retainCount to debug things, if you are not very confident you know what's happening under the cocoa hood.

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