NSString *string = @“someString” vs NSString *string = [[NSString alloc] initWithFormat@“%@”, string]

心不动则不痛 提交于 2019-12-19 04:16:05

问题


If I have a method

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

and I call

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

Do I need to do something like

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

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.


回答1:


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.




回答2:


If you use : NSString *str = @"". It is kind of a constant, you don't need to do any memory management.

If you call from a method : NSString *str = [NSString stringWithFormat:@""], the str is already autoreleased.

If you manually alloc, init. You need to call release, or autorelease yourself.

The general memory convention is : if you do something with new, alloc, retain, or copy, you need to release it yourself, any other cases, the object is autoreleased, don't release it



来源:https://stackoverflow.com/questions/3270071/nsstring-string-somestring-vs-nsstring-string-nsstring-alloc-initwit

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!