Howard
Howard

Reputation: 19825

Why no retain is needed 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 no retain is needed for stringWithString?

Can you show me an example where retain is needed?

Upvotes: 3

Views: 170

Answers (4)

Alex Terente
Alex Terente

Reputation: 12036

You can start by reading Memory Management Programming Guide and look at this tutorial.

Upvotes: 1

Damien
Damien

Reputation: 2421

Have a look at Memory Management Rules from Apple. In your case, you did not alloc/retain/net the NSString so you don't "own" it and therefore you do not need to release it.

Internally, NSString would return you a autoreleased object. If you don't retain it then you'll lose reference to it if it gets dealloced by an autorelease pool.

Upvotes: 0

Ole Begemann
Ole Begemann

Reputation: 135578

Why no retain is needed for stringWithString?

Because the autorelease pool is not being drained between line 2 and line 3 (as it would be in a Cocoa app as soon as your code returns control to the run loop).

Upvotes: 2

JustSid
JustSid

Reputation: 25318

Its because the autorelease pool had no time to drain its content. Here is a crashing example:

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

The autorelease pool that holds the string in your example belongs to 99% to the current runloop which creates a new pool at the begin of the event loop and then drains it at the end.

Upvotes: 4

Related Questions