How NSMutableString works under the hood ?

I want to understand how it manages memory allocation if i need more memory later than the memory i specified during initialisation . Does it allocates new chunk of memory and dellocate older memory or does it already allocated more memory than i asked for in first place? Just want to understand how exactly this calculation is done ?

And i do initialisation of NSMutableString in swift , will these same principle of expension applied there ?

Answered by DTS Engineer in 816401022

NSMutableString is a complex thing and the exact details of how it works are subject to change. So it’s best to only depend on its documented API rather than on how it’s implemented. Which brings us to:

Does it allocates new chunk of memory and dellocate older memory or does it already allocated more memory than i asked for in first place?

NSMutableString has the concept of a capacity, which you set when you create the string. This lets you handle the common case where you’re creating a string and you know in advance how large it’s likely to get.

IMPORTANT As the docs say, this is a hint, not an API contract. Also, it’s only a hint for the initial capacity; it’s fine for the string to grow beyond that capacity.

And i do initialisation of NSMutableString in swift … ?

If you use NSMutableString from Swift then you should expect it to behave the same as it would from Objective-C. However, the Swift type for this is String, and the behaviour of String can vary a lot depending on how you got the string.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

Accepted Answer

NSMutableString is a complex thing and the exact details of how it works are subject to change. So it’s best to only depend on its documented API rather than on how it’s implemented. Which brings us to:

Does it allocates new chunk of memory and dellocate older memory or does it already allocated more memory than i asked for in first place?

NSMutableString has the concept of a capacity, which you set when you create the string. This lets you handle the common case where you’re creating a string and you know in advance how large it’s likely to get.

IMPORTANT As the docs say, this is a hint, not an API contract. Also, it’s only a hint for the initial capacity; it’s fine for the string to grow beyond that capacity.

And i do initialisation of NSMutableString in swift … ?

If you use NSMutableString from Swift then you should expect it to behave the same as it would from Objective-C. However, the Swift type for this is String, and the behaviour of String can vary a lot depending on how you got the string.

Share and Enjoy

Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"

How NSMutableString works under the hood ?
 
 
Q