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.
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.
I often use
+stringWithString:
when I need to create anNSMutableString
but start it with an initial value. For example:As "Andy" points out in #318666, it's related to memory management, quoting:
(Taken from here)
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.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.
You might have a NSMutableString (or some home-grown NSString subclass) that you want to duplicate.
Of course, you can also just make a copy:
but you own the copy and must release or autorelease it.
Returns a string created by copying the characters from another given string
It is equivalent to