-1

i want to ask a question on NSString, the question is if

NSString str = @"Hello";
str = [str stringByAppendingString:@"World"];

if we NSLog the str we would get an output - HelloWorld!

So my question is if str is NSString class variable an its an static one (which can not be changed once it is defined) then how can we able to change it, (Note that I have used same NSString object str).

rmaddy
  • 314,917
  • 42
  • 532
  • 579
Bharat Modi
  • 4,158
  • 2
  • 16
  • 27

2 Answers2

1

You haven't declared the string as static, but NSString is immutable. You are creating a new string and replacing str. Many Obj-C classes have a mutable type, so if you intended to modify your string as in this example, you might want something more like:

NSMutableString *str = [NSMutableString stringWithString:@"Hello"];
[str appendString:@" World"];

Note, @"Hello" is a NSString, so attempting to initialize a NSMutableString using that syntax would result in an error.

valdarin
  • 921
  • 10
  • 20
  • Thanks! Got my answer, actually it was asked me in an interview, but i couldn't be able to answer it correctly at that time, i can explain it more clearly if someone ask me. – Bharat Modi Aug 22 '14 at 06:24
0

Actually, static variables can be changed once they are defined. Static variables are simply maintained throughout all function/instance calls. You can find a more detailed explanation here static variables in Objective-C - what do they do?. So the result would be the same. If the variable were defined as const (which cannot be changed) then you would get a compiler error. Generally speaking, the best way to figure these types of things out is to just try them on your own. If it's just a matter of writing a couple lines of code, or changing a keyword, what does it hurt?

Community
  • 1
  • 1
jpecoraro342
  • 784
  • 6
  • 6
  • This answer kind of misses the point, since the OP is mistaken about having a static variable. – jscs Jul 27 '14 at 18:34
  • I might have misunderstood the question. I understood it as "if str were declared static, how do you change it's value?" – jpecoraro342 Jul 27 '14 at 18:43