Pregunta

this is a more theoretical question than pratical;

Assuming that i have two Strings, one normal and one mutable, if i do:

NSMutableString *prova = [[NSMutableString alloc] init];
NSString *prova2 = [[NSString alloc] init];
[prova appendFormat:@"%@",@"CIAO"];
prova2 = prova;
NSLog(@"String: %@",prova);
NSLog(@"String2: %@",prova2);
[prova setString:@""];
NSLog(@"-String: %@",prova);
NSLog(@"-String2: %@",prova2);

Then the result is:

2013-04-22 22:01:53.604 CodeTest[6974:303] String: CIAO
2013-04-22 22:01:53.605 CodeTest[6974:303] String2: CIAO
2013-04-22 22:01:53.605 CodeTest[6974:303] -String: 
2013-04-22 22:01:53.606 CodeTest[6974:303] -String2:

Why does it behave like this? I just wanna find it out, because i've never encountered such thing before while programming in python, php or C++ (I think i was never confronted with so many different data types as in Obj-c :P )

Thanks

Just in case anyone wants to know how to get over it here is the right code i used to assign the value to the string without losing it after the "blanking" (sostitute to prova2 = prova):

prova2 = [NSString stringWithString:prova];
¿Fue útil?

Solución

Remember that the NSString and NSMutableString variables are pointers. That means when you assign prova2 = prova you're really changing prova2 to point to prova, and the value you assigned to prova2 is lost.

So when you assign the empty string to prova both variables point to @"".

Otros consejos

prova2 = prova;

This doesn't assign the contents of the string in prova to the string in prova2, it just makes prova2 point to the same object as prova, effectively leaking the string that prova2 used to point to. So even though prova2 is declared as a NSString*, it now points to a NSMutableString.

In addition to Richard Brown's great response, that's what you'd like to do instead for desired behaviour:

[prova2 setString: prova];

instead of

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