iOS memory management about NSString - objective-c

Is there any different between
NSString * str = #"123";
and
NSString * str = [[NSString alloc] initWithString:#"123"];
from compiler's aspect?

Theoretically yes; in implementation detail, probably not.
In the first case, the compiler creates a constant string and assigns a pointer to it to the variable str. You do not own the string.
In the second case, the compiler creates a constant string (as before) but this time it is used by the run time as a parameter in initialising another string that you do own (because the second string was created using alloc).
That's the end of the stuff you need to know.
However, there is a lot of optimisation that goes on. Because NSStrings are immutable, you'll find that initWithString: actually just returns the parameter. Normally, it would retain the parameter before returning it to you (because you are expecting to own it) but literal strings have a special retainCount (INT_MAX I think) to stop the run time from ever trying to deallocate them. So in practice, your second line of code produces identical results to the first.
This incidentally, is why it is incorrect top say the string is autoreleased in the first case, because it isn't. It's just a constant string with a special retain count.
But you can and should safely ignore the implementation detail and just remember, you don't own the string in the first case, but you do own it in the second case.

Lots of differences. The most important is that you own the second string so you're responsible for releasing it (as is the case whenever you get an object from the init family of methods).
Another is that the former creates a string literal, and if you make a new string with the same literal, they will be pointers to the same object. If you do this:
NSString * str1 = #"123";
NSString * str2 = [[NSString alloc] initWithString:#"123"];
NSString * str3 = #"123";
Then str1 == str2 is false, but str1 == str3 is true. (Of course, the string content is the same, so isEqual: will return true. Also, while this does make for faster comparison, you probably shouldn't use it because it's an implementation detail and could in theory change in the future).

Yes, in the first case you do not own the string and you are not responsible to release it.
In the second case, instead, you are calling alloc thus you become the owner of the object and you must call release on it when you have done, otherwise it will become a memory leak.
In general, if the method you use to get your object contains "new","alloc","copy" or "mutableCopy" then you are the owner of the object and you are responsible to release it.
Check the memory management rules

Yes. The first is assignment of an NSString, and in the second the alloc (which means you need to release it in some way later) and initWithString: method are getting called.

Yes , first statement creates an autorelease object.
Second one creates an object occupying some memory and you have to release it after using it.

The main important difference about memory (your question title) is:
when you do:
NSString* myString = #"my text";
you are allocating an object of NSConstantString type.
The difference with NSString is:
NSConstantString is statically allocate, while NSString is dynamically allocated.

Related

Lifespan of NSString cStringUsingEncoding return value

I have an NSTextField and get its contents like so
NSString *s = [textField stringValue]
Now I want to convert this NSString to a string that my platform-independent C code can handle. Thus I'm doing:
const char *cstr = [s cStringUsingEncoding:NSISOLatin1StringEncoding];
What I don't understand now is how long this "cstr" pointer stays valid. Apple docs for cStringUsingEncoding say:
The returned C string is guaranteed to be valid only until either the
receiver is freed, or until the current memory is emptied, whichever
occurs first. You should copy the C string or use
getCString:maxLength:encoding: if it needs to store the C string
beyond this time.
Two questions about this:
I suppose the aforementioned "receiver" is the NSString returned by the [textField stringValue]. Since I don't own this NSString how can I tell when this will be freed? Is it safe to assume that this NSString won't be freed before the NSTextField widget will be freed?
What does "until the current memory is emptied" mean precisely? I don't understand this at all.
Of course, I could just go ahead and make a copy but I'd like to understand how long the string pointer returned by cStringUsingEncoding is valid.
I know there are several similar questions here but none could really answer my question since in my case, the owner of the NSString is the NSTextField widget and I don't know when this widget will release the NSString or if it stays valid for the complete lifespan of the widget itself.
I suppose the aforementioned "receiver" is the NSString returned by the [textField stringValue]
yes, in this case the receiver is s
Since I don't own this NSString how can I tell when this will be freed?
you don't. you should retain s by storing it in an instance variable for as long as you need it
Is it safe to assume that this NSString won't be freed before the NSTextField widget will be freed?
no, because you don't know what or how the text field returned s to you
What does "until the current memory is emptied" mean precisely? I don't understand this at all.
good question. also, hard to tell, because you don't own the string or know about its underlying implementation. say it was a mutable string that was mutated and had to reallocate memory...
you can be pretty sure of your safety if you copy s, store the copy in an instance variable and then use the copy to get the C string (or just copy the C string).
Receiver for sure means the string s, and the danger to cstr is clear when s is freed. I think the phrase "or until current memory is emptied" is a documentation bug introduced by ARC. It can be read as "or until an ARC-implied release is executed".
See the doc quoted here in 2010 as evidence. I think the author, probably searching for 'autorelease pool' for places to update the docs, was grasping for a harmless, ARC-compatible synonym for "or until the current autorelease pool is emptied". I think it would have been better to just drop the disjunction.
Anyway, either take control of the NSString, or copy the cstring.

Is there risk in assigning the output of stringByAppendingString to the same instance?

Is there risk in assigning the output of -[NSString stringByAppendingString] to the same instance? I remember running into issue with this but don't recall the exact situation.
string = [string stringByAppendString:#"more string"];
Before your line executes, string is a pointer to one NSString instance. Afterward, string points to a different instance. You haven't changed the original, you just don't have a pointer to it anymore.
If you're using ARC (the default), or the original string was autoreleased or is a string literal constant, there's no further cleanup to worry about.

Best allocation for NSString when alternating between constant and non constant strings

I would like some help better understanding the memory characteristics of Strings in Cocoa.
The app I am working with uses one view controller and n tool objects. The View controller lives for the life of the program but the tool objects are allocated and released.
Suppose I have a string toolName_ and in my implementation I configure the incoming tool object: if the object does not have a tool name, I want to set the toolName_ string to #"not set". If the tool has a name I want to set the string to the name of the tool.
I would like to know the proper way to store the incoming value into the toolName_ given that sometimes this will be an allocated object and sometimes this will be a constant string.
-(BOOL)setToolObject: ToolObject: obj{
ToolObject someObj = nil;
someObj = [[ToolObject alloc]initWithObject obj];
if(someObj != nil){
if(! [someObj.toolName isEqualToString: #""]){
self->toolName_ = Which method should I use given the above question?
The last instance may have been a constant string but may not have.
[self->toolName_ release] (can I send a release message to a constant
string without causing a problem?)
self->toolName = [[NSString alloc]initWithString:someObj.toolName];
OR
self->tool name = [NSString stringWithString: someObj.toolName];
This method is self releasing but I don't own it and I'm still not sure
what happens to the constant string if it existed. I think I read it's
not recommended to use this on member vars.
}else{
self->toolName_ = #"not set";
}
return YES;
}else{
return NO;
}
}
Advice appreciated.
I highly suggest to (possibly) use ARC, and if you can't use it (or maybe you just want to understand how memory management works?), to don't send retain and release messages from outside the class. Instead you should do this in the accessors.
So you should create a retain or copy property (usually with immutable strings is preferable to use copy, because they may be assigned to mutable strings, so making invalid the assumption that you are working with an immutable - thus thread safe - property).
So in your case I suggest a setter like this one:
- (void) setToolName: (NSString*) toolName
{
if(_toolName== toolName)
return;
[_toolName release];
_toolName= [toolName copy];
}
This way you're doing it fine, you shouldn't be concerned about what is the retain count of the setter argument. In case it is a string literal which has an unknown retain count, the object does not even respond to a release message, so it will stay alive for all the program (unlike it seems it is efficient because it avoids the overhead of creating an object at runtime). If you copy an immutable object (unless it something like a cached NSNumber, or a string literal), the code just does a simple assignment and the retain count gets increased.
So if you just follow the rule of "I retain (or copy) what I need to use, I release what I don't need to use anymore", you're doing it fine and you shouldn't worry about what happens in particular case like with string literals.

Usage of NSString and NSMutableString objects in Objective C

I need to use a bunch of string variables throughout my program. I reassign some of them quite often, while others are stuck with the same value during execution.
What's the best practice here?
In the first case, the variables should be NSMutableString and I should cast them to NSString (using the copy method) whenever they need to be arguments of functions that require NSString objects. Is that right?
When I reassign them to other constant values, I shouldn't have to dispose the previous content, right?
As for NSString objects, if I need to assign a new value to them, I guess I should deallocate them, allocate them again, and then assign the new value. Is that correct?
Unless you're actually modifying a string, you shouldn't use NSMutableString. You're reassigning the whole string to a new value, so stay with a regular NSString. Use the autoreleased versions, because that'll be more efficient than alloc/init/release all the time. You could also just reassign your strings to constants if you know what they'll be assigned to.
In the first case, the variables should be NSMutableString and I should cast them to NSString (using the copy method) whenever they need to be arguments of functions that require NSString objects. Is that right?
Well, you could do it that way, but it would be really inefficient. Remember inheritance—an NSMutableString is an NSString, just with some new stuff tacked on. A simple cast will do the trick:
NSString *string = (NSString *)aMutableString;
Even better though, you don't even have to do that. Because of inheritance, you can directly pass in a mutable string wherever a regular string is required, no casting required. That's the beauty of inheritance.
When I reassign them to other constant values, I shouldn't have to dispose the previous content, right
For neither mutable or immutable strings. Old values are simply overwritten in memory—nothing to dispose of there. As far as the memory management goes, it's really not efficient to literally be creating new strings all the time. Just reassign them. You will never need to alloc/init one string more than once, and that single init should be balanced by a single release.
Addendum: When Should You Use Mutable?
A mutable string should be used when you are physically changing the value of the existing string, without completely discarding the old value. Examples might include adding a character to the beginning or the end, or changing a character in the middle. With a mutable string, you can do this "in place"—you'll just modify the existing string. By contrast, an immutable string, once its value is set, cannot change that value. NSString has methods such as stringByAppendingString:, which does add a string to an existing one—but it returns a new string. Behind the scenes, NSString has copied your old string to a new (larger) memory location, added the argument, and returned the new string. That copying is a lot less efficient (relatively speaking, or if you have to do it a lot).
Of course, there's nothing stopping you from physically assigning one string to another. Old values will be overwritten. Most NSStrings, including the #"String Constants", are autoreleased. If you are creating a new string and you decide to alloc/init, you can then assign it to another value without consequence:
myString = anotherString;
myString = myTextField.text;
You can do this with both mutable and immutable strings. The main takeaway is that you should only use mutable when your changing the string itself. But you can change the variable with both mutable and immutable strings without compiler or runtime issues (short of memory management, but most of it is autoreleased anyway).
As for NSString objects, if I need to
assign a new value to them, I guess I
should deallocate them, allocate them
again, and then assign the new value.
Is that correct?
You don't deallocate NSString if you didn't allocated it before, like here:
NSString *string = [NSString stringWithFormat:#"Hello"];
You only need to deallocate it when you call alloc:
NSString *string = [[NSString alloc] initWithString:#"Hello"];
[string release];
The only difference between NSMutableString* and NSString* is that mutable string can be changed.
You don't have to cast anything, since NSMutableString is a subclass of NSString, nor take different memory measures ( so you are right * ).
If you need a modifiable version of a string you just do
NSMutableString* myMutableString = [NSMutableString stringWithString:myString];
You should not 'copy' anything.
Note that if you call :
NSString* myString = myMutableString;
myString is still a mutable String.
So if for any reason (security...) you relly need unmutable strings, you have to call
NSString* myString = [NSString stringWithString:myMutableString];
* you are right, but you could also call [replaceCharactersInRange:withString:] on the mutable string. if there is enough space from previous allocation, then it may be faster, since there is no destruction and new allocation to do.
( Added later : forgot the setString: method )

Differences between NSStrings?

I understand that the v03 example creates an object that I own and must ultimately release. What I would like to know is are there any differences between the first two(v_01 & v02), or are they essentially the same?
// Version_01
userName = #"Teddy";
// Version_02
userName = [NSString stringWithString:#"Gary"];
// Version_03
userName = [[NSString alloc] initWithString:#"Caroline"];
... some code
[userName release];
gary
They are all similar, but there are some slight differences between the three.
The first one is a pointer to a string constant. The string Teddy is stored in read-only memory, and userName is a pointer to this string constant. You need not (and cannot) retain or release this object, since it exists "permanently" (that is, for the duration of the program).
The second one is an autoreleased string object with the contents Gary. When returned to you, it has a release count of 0. It may be retained and released as needed.
The third one is similar to the second one, but it is not autoreleased, so it has a retain count of 1 when it is initially returned to you. Like the second one, it may be retained and released as needed.
Most of the differences in these instances is how the memory is managed. If you want a clearer view of what's happening in the background, you might want to peruse the Objective-C Memory Management Guide.
// Version_01
userName = #"Teddy";
This is a String constant that does not have any memory management associated with it. The memory used to hold the value is part of the memory in which the code resides in (essentially). retain and release calls on the variable will be ignored.
// Version_02
userName = [NSString stringWithString:#"Gary"];
This is an autoreleased instance of an NSString object. Its retain count is currently one and will be released by the autorelease pool soon unless it is retained.
// Version_03
userName = [[NSString alloc] initWithString:#"Caroline"];
[userName release];
This is a managed instance of an NSString. When it is first initialized, its retain count is one. After releasing it, the retain count went down to zero, therefore, its memory will be deallocated. Referring to the variable userName after releasing it will cause an EXE_BAD_ACCESS error.
The first two or essentially the same
The latter one is not however as userName would be an invalid string object at that point.
However changing it to
userName = [[[NSString alloc] initWithString:#"Caroline"] autorelease];
would render it effectively the same as the previous two.
version 01: is a string constant....
version 02: is an auto-released NSString created by copying a constant.
Practically, there are no differences, as long as you don't attempt to use the Version_03 string after you release it. If you want to do that, you'll need to autorelease it instead.