+[NSString stringWithString:] — what's the poi

2019-01-09 06:06发布

As NSString strings are immutable, what is the value of the stringWithString: class method?

I get the utility when used with NSMutableString, I just didn't see the utility with the NSString class.

7条回答
小情绪 Triste *
2楼-- · 2019-01-09 06:33

I often use +stringWithString: when I need to create an NSMutableString but start it with an initial value. For example:

NSMutableString * output = [NSMutableString stringWithString:@"<ul>"];
for (NSString * item in anArray) {
  [output appendFormat:@"<li>%@</li>", item];
}
[output appendString:@"</ul>"];
查看更多
Juvenile、少年°
3楼-- · 2019-01-09 06:34

As "Andy" points out in #318666, it's related to memory management, quoting:

The difference between initWithString and stringWithString is that stringWithString returns an auto-released pointer. This means that you don't need to release it specifically, since that will be taken care of next time that the auto-release pool cleans up any auto-released pointers.

initWithString, on the other hand, returns a pointer with a retain count of 1 - you do need to call release on that pointer, or else it would result in a memory leak.

(Taken from here)

查看更多
何必那么认真
4楼-- · 2019-01-09 06:41

As another use case, if (for whatever reason) you create your own subclass of NSString or NSMutableString, stringWithString: provides a handy way to instantiate it with an instance of either NSString, NSMutableString, or MyCustomString.

查看更多
在下西门庆
5楼-- · 2019-01-09 06:44

Also, if you have a pointer to an NSString, it may actually be a subclass of NSString like NSMutableString. So, if you want to store the string and be guaranteed that it doesn't change, you should make a copy of it, hence stringWithString exists.

查看更多
啃猪蹄的小仙女
6楼-- · 2019-01-09 06:47

You might have a NSMutableString (or some home-grown NSString subclass) that you want to duplicate.

NSMutableString *buffer = [NSMutableString string];
// do something with buffer
NSString *immutableStringToKeepAround = [NSString stringWithString:buffer];

Of course, you can also just make a copy:

NSMutableString *buffer = [NSMutableString string];
// do something with buffer
NSString *immutableStringToKeepAround = [[buffer copy] autorelease];

but you own the copy and must release or autorelease it.

查看更多
兄弟一词,经得起流年.
7楼-- · 2019-01-09 06:48

Returns a string created by copying the characters from another given string

[NSString stringWithString:@"some string"]

It is equivalent to

[[[NSString alloc] initWithString:@"some string"] autorelease]
查看更多
登录 后发表回答