本文介绍了NSString * string = @" someString" vs NSString * string = [[NSString alloc] initWithFormat @"%@",string]的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如果我有方法

- (void) myMethod:(NSString *)string {
    [Object anothermethodWithString:string];
}

我打电话

[Object myMethod:@"this is a string with no alloc statement"]

我是否需要做类似

- (void) myMethod:(NSString *)string {
    NSString *string2 = [[NSString alloc] initWithFormat:@"%@", string];
    [Object anothermethodWithString:string2];
    [string2 release];
}

而不是我之前使用myMethod的方式?我有一个行为错误的代码似乎是由一个字符串被自动释放而另一个方法中的第二个方法被调用(如示例中所示)。我有myMethod的第二种方法解决了我的所有问题。

instead of the way I had myMethod before? I have misbehaving code that seems to be caused by a string being auto-released while a second method within another method is being called (like in the example). The second way I have myMethod fixed all of my problems.

那么非分配字符串是一个自动释放的字符串吗?我问这个问题是另一个问题的后续问题(这完全不相关,也就是我创建这篇文章的原因),有几个消息来源说我不需要重新分配字符串。我很困惑,因为我的代码的行为告诉我。

So is a "non-alloc" string an auto-released string? I asked this question as a follow up to another question (which was completely unrelated and is why I am creating this post), and a few sources said that I don't need to reallocate the string. I am confused, because the behavior of my code tells me otherwise.

推荐答案

戴夫说得对。您只需要担心在 new alloc release c $ c>,保留,或复制

Dave's got it right. You only need to worry about calling release on objects that you new, alloc, retain, or copy.

上面的规则很有效,但是如果你很好奇并且想要了解很多细节,我建议你阅读。它是免费的,从基本概念到很多细节。

The above rule works very well, but if you're curious and want to get into a lot of detail, I suggest reading the Memory management Programming Guide from Apple's docs. It's free and goes from basic concepts into a lot of details.

这篇关于NSString * string = @" someString" vs NSString * string = [[NSString alloc] initWithFormat @"%@",string]的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-16 01:11