Pregunta

I want to know the difference between nil and @"" in NSMutableString.

I need to clean string value in NSMutableString every second.

So

myMutableString = nil;

or

myMutableString = @"";

Which one is better to clean and why?

¿Fue útil?

Solución

UPDATE


In the case of a mutable string, you have to alloc/init it first like this:

NSMutableString *myMutableString = [[NSMutableString alloc] init];

Maybe you have done that, but then you have to reset the string like this:

[myMutableString setString: @""];

So instead of writing myMutableString = @"", use the code above.


If you assign myMutableString to nil it is not a valid pointer/object and cannot respond to messages or actions. If you actually set it to @"", it is a totally valid object which can respond to messages, methods and actions, it is just contains a string with a length of 0.

myMutableString = nil;

[myMutableString appendString: @"It now contains a valid string!"]; 

This cannot happen since the string is nil

myMutableString = @""; 

[myMutableString appendString: @"It now contains a valid string!"]; 

This can happen, myMutableString is a valid object and can respond to messages. And guess what, it now has a string!

So, a string object can still be initialized and have have an actual string value without any characters. Just like an array can be valid and have 0 objects inside it. Otherwise, how would you add to it!?

However, In an NSMutableString's scenario, you may have to actually alloc-init it.... somebody please clarify.

Obviously, assigning to @"" is better, it actually depends on your scenario though. I don't know why you would want to assign to nil, unless you are reassigning the variable to a new string object.

Otros consejos

None of them

use

[myMutableString setString: @""];

to reset your string.

Your object remains the same. You invoke a method that clear its content.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top