Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does a NSMutableString exactly work?

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?

like image 959
TalkingCode Avatar asked Dec 22 '22 01:12

TalkingCode


1 Answers

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.

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 variable a that 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:

NSString *a;
NSMutableString *b;

Both are references to -- addresses of -- some allocation in memory. The only difference is during compile time, b will be treated differently than a and the compiler will not complain if, say, you use NSMutableString methods when calling b (but would when calling a).

As far as how NSMutableString works, 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 of free(); malloc(); memcpy();.

I'd suggest you revisit the Objective-C Programming Guide or, possibly, a C programming manual.

like image 55
bbum Avatar answered Mar 07 '23 16:03

bbum