简体   繁体   中英

When are temporary NSStrings released?

I'm trying to hunt down a memory leak in one of my iOS programs. I think I have it nailed down to the a couple of lines similar to these:

NSString *s1Upper = [s1 uppercaseString];
s1Upper = [s1Upper stringByTrimmingCharactersInSet: 
    [NSCharacterSet whitespaceCharacterSet]]; 

(I know these two lines do not make sense from a logic perspective, the just illustrate the memory question I have.)

Lets say that s1 is @"abc " (ending in a space). The way I understand NSStrings, s1Upper points to one NSString (@"ABC " ending in a space) after the first line of code. After the second line, it points to a different NSString (@"ABC" without a space).

My question: When is the first NSString released?

My guess is that it gets released when the current NSAutoreleasePool is drained. In that case, I have a followup question: How can I influence this and control the draining?

It's autoreleased, that is it is released when the autorelease pool is drained. Typically at the end of the current run loop.

In this case you can't really change it. What you can do is retain it, and release it later when you know it's safe. That will prevent it from being deallocated with the auto release pool drains.

You can't stop auto these objects from going to the autorelease pool because the internal implementation of the method does that. You can only make sure that the autorelease does not drop the retain count to zero by retaining the object.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM