Why save is not required in my code, but it works

I have a class

@implementation MyClass

- (void) foo    
{    
    ivar = [NSString stringWithString:@"ivar"];
}

- (void) bar    
{    
    NSLog(@"%@", ivar);
}

And main.m

MyClass * m = [[MyClass alloc] init];
[m foo];
[m bar];

Why doesn't stringWithString need saving?

Can you show me an example where to save?

+3
source share
4 answers

This is because the abstract pool did not manage to deplete its contents. Here is an example:

NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
MyClass *m = [[MyClass alloc] init];
[m foo];
[pool drain];
[m bar];

The autoresist pool that contains the line in your example is 99% of the current runloop, which creates a new pool at the beginning of the event loop and then depletes it at the end.

+4
source

Why doesn't stringWithString need saving?

Since the auto-calculation pool does not merge between line 2 and line 3 (as it would be in a Cocoa application, as soon as your code returns control to the launch cycle).

+2
source
+1
source

See Apple's Memory Management Rules . In your case, you did not allocate / save / carry NSString so that you do not "own" it, and therefore you do not need to release it.

Internally, NSString will return an auto-implemented object to you. If you do not save it, you will lose the link to it if it is freed by the autorun pool.

0
source

All Articles