what is difference between mutable and immutable

后端 未结 8 1826
感动是毒
感动是毒 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)

提交回复
热议问题