what is difference between mutable and immutable

后端 未结 8 1825
感动是毒
感动是毒 2020-12-24 15:39

what is difference mutable and immutable

like

NSString and NSMutableString.

NSArray and NSMutableArray.

NSDictionary and NSMutableDictionary

相关标签:
8条回答
  • 2020-12-24 16:13

    Mutable objects can be modified, immutable objects can't.

    Eg: NSMutableArray has addObject: removeObject: methods (and more), but NSArray doesn't.

    Modifying strings:

    NSString *myString = @"hello";
    myString = [myString stringByAppendingString:@" world"];
    

    vs

    NSMutableString *myString = @"hello";
    [myString appendString:@" world"];
    

    Mutable objects are particularly useful when dealing with arrays,

    Eg if you have an NSArray of NSMutableStrings you can do:

    [myArray makeObjectsPerformSelector:@selector(appendString:) withObject:@"!!!"];
    

    which will add 3 ! to the end of each string in the array.

    But if you have an NSArray of NSStrings (therefore immutable), you can't do this (at least it's a lot harder, and more code, than using NSMutableString)

    0 讨论(0)
  • 2020-12-24 16:14

    The basic difference is:

    • NSStrings cannot be edited, only reassigned. This means when the value of an NSString changes, it is actually pointing to a new location in memory.

    • NSMutableString objects can be edited and maintain the same pointer.

    A common practical difference is:

    • If you create 1 NSString and then assign another one to it, then edit either one of them, they will now be pointing to different strings.

    • If you do the same thing with NSMutableStrings, but then just edit one of them (not reassign it), they will both be pointing to the newly edited object.

    0 讨论(0)
提交回复
热议问题