user2825086
user2825086

Reputation:

NSString and NSMutableString memory considerations

I am trying to wrap my head around NSString and NSMutableString, and how they affect memory.

In my research, I've concluded that if I create an NSString object and give it a value, then change the value later, the original object is replaced by another with the new value.

My question is, in the case of changing the value of an NSString. When the value of the NSString is changed and the object pointed to is replaced by a new object, what happens to the original object? Is this a memory leak?

Thanks! V

Upvotes: 3

Views: 362

Answers (2)

Antonio
Antonio

Reputation: 72750

NSStrings can contain string literals, which are compile time constants, and string objects, which instead are instantiated dynamically at runtime.

In case of string literals, there is no dynamic instantiation, so they won't affect memory at runtime. Assigning a literal value to a NSString variable

NSString *myString = @"string1";

then assigning another literal value

myString = @"string2";

doesn't make any change to the amount of available memory.

In case of string objects instead memory does change. If you have a variable of type NSString and assign it a dynamic string, such as

NSString *myString = [NSString stringWithFormat:@"String %d", 1];

a new NSString instance is allocated, initialized with the provided string, and assigned to the myString variable.

If later you assign a new dynamic value

myString = [NSString stringWithFormat:@"String %d", 2];

a new NSString instance is created, but it doesn't replace the old one. Both are instantiated and in memory.

When using ARC though the first NSString instance, if no longer referenced, will be released because not being used. This is handled automatically, so nothing must be done from code.

Maybe you're more interested in the fact that at some time the new and old instances use memory - but that's temporary until the unused instance is released.

To answer to your concern, no, there is no memory leak. String literals persist for the entire app lifetime, since they are constants. String objects are allocated and released (deallocated), and deallocation is automatically handled by ARC.

Of course this is a general concept that applies to any dynamically instantiated class, not just NSString - but doesn't apply to primitive data type (int, boolean, float, etc.), because variables of those types hold the actual value, not a pointer to the area in memory where the value is. In case you are wondering, primitive data types don't generate memory leaks.

Upvotes: 2

Tancrede Chazallet
Tancrede Chazallet

Reputation: 7245

The original NSString will be released by the system and so, won't cause any leak.

Upvotes: 1

Related Questions