JoeS
JoeS

Reputation: 231

Is memory freed when the length of an NSString is reduced or do I have to do something more?

If I have the following code:

NSString* test = @"12345... 1Kb worth of characters";
test = [test substringFromIndex:512];

Then would the memory consumed by test be halved (from 1024 to 512 bytes) or do I have to do something to tell it to release the memory?

Thanks,

Joe

Upvotes: 2

Views: 110

Answers (3)

Jacob Relkin
Jacob Relkin

Reputation: 163308

Since the memory which you refer to is allocated statically - in this case you are okay.

NSString* test = @"12345... 1Kb worth of characters";
test = [test substringFromIndex:512];

However, in the following case:

NSString *s = [@"some long string" retain];
s = [s substringFromIndex:someLongNumber];

You would have a memory leak, since the memory occupied by s at the point of the second assignment will have lost its reference, thereby rendering you unable to eventually release the memory that was previously occupied in the location referenced by s.

Upvotes: 2

Helge Becker
Helge Becker

Reputation: 3253

Yes and no. No, as long the String isn't retained somewhere else the memory gets freed by the garbage collector sometime later. (Yes there is one, we just have more control when/if an object gets destroyed and the entire method isn't exactly by the book a garbage collector, but thats details.)

Yes due sometimes later. For a time, you use the memory of booth objects. :)

Upvotes: 0

Nekto
Nekto

Reputation: 17877

After such call new memory for substring will be allocated. But your string test is marked as autoreleased. So previous value of test will be automatically released and new value will be assigned. Notice that new value (substring) will be too autoreleased and you don't need to release it manually.

Upvotes: 2

Related Questions