Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

+[NSString stringWithString:] -- what's the point?

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.

like image 791
jeff7091 Avatar asked Oct 23 '09 23:10

jeff7091


People also ask

What does NSString mean?

A static, plain-text Unicode string object that bridges to String ; use NSString when you need reference semantics or other Foundation-specific behavior.

Do I need to release NSString?

If you create an object using a method that begins with init, new, copy, or mutableCopy, then you own that object and are responsible for releasing it (or autoreleasing it) when you're done with it. If you create an object using any other method, that object is autoreleased, and you don't need to release it.


1 Answers

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.

like image 113
Don McCaughey Avatar answered Sep 20 '22 17:09

Don McCaughey