I know all instances of NSString are inmutable. If you assign a new value to a string new memory is addressed and the old string will be lost.
But if you use NSMutableString the string will always keep his same address in memory, no matter what you do.
I wonder how this exactly works. With methods like replaceCharactersInRange I can even add more characters to a string so I need more memory for my string. What happens to the objects in memory that follow the string? Are they all relocated and put somewhere else in memory? I don’t think so. But what is really going on?
That isn’t how mutability works, nor how references to NSStrings work. Nor how pointers work.
A pointer to an object —
NSString *a;declares a variableathat is a pointer to an object — merely holds the address in memory of the object. The actual object is [generally] an allocation on the heap of memory that contains the actual object itself.In those terms, there is really no difference at runtime between:
Both are references to — addresses of — some allocation in memory. The only difference is during compile time,
bwill be treated differently thanaand the compiler will not complain if, say, you useNSMutableStringmethods when callingb(but would when callinga).As far as how
NSMutableStringworks, it contains a buffer (or several buffers — implementation detail) internally that contain the string data. When you call one of the methods that mutate the string’s contents, the mutable string will re-allocate its internal storage as necessary to contain the new data.Objects do not move in memory. Once allocated, an allocation will never move — the address of the object or allocation will never change. The only semi-exception is when you use something like
realloc()which might return a different address. However, that is really just a sequence offree(); malloc(); memcpy();.I’d suggest you revisit the Objective-C Programming Guide or, possibly, a C programming manual.