The final word on NSStrings: Mutable and Immutable

后端 未结 6 608
忘掉有多难
忘掉有多难 2020-12-16 23:14

I\'ve read in several books... and online... about immutable and mutable strings. They claim \"immutable strings\" can\'t be changed. (But they never define \"change\".)

6条回答
  •  有刺的猬
    2020-12-17 00:07

    If I declare a variable:

    NSString * var;
    // Here some code giving a new value to var
    

    What is immutable is the object pointed to by var, not var itself.

    This means that I cannot change anything of the object pointed to by var, but I can change which object is pointed to.

    None of the operations you mention is allowed on var, but you can assign var with another different string:

    NSString * anotherVar;
    // Here some code giving a new value to anotherVar
    
    var = anotherVar; // This is allowed (with a memory leak if GC is disabled)
    
    // The following is also allowed: -stringWithFormat: creates a new object
    var = [var stringWithFormat:@"%@ with more chars", var];
    

提交回复
热议问题