iPhone – Why don’t you need to keep 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 to be retained?

Can you tell me an example that needs to be kept?

This is because the auto-release pool has no time to consume its content. This is an example of a crash :

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

In your example, the auto-release pool that saves the string belongs to 99% of the current runloop, it Create a new pool at the beginning of the event loop, and then drain it at the end.

I have a class

@implementation MyClass

- (void) foo
{
ivar = [NSString stringWithString:@"ivar"];
}
< br />- (void) bar
{
NSLog(@"%@", ivar);
}

and main.m

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

Why stringWithString does not need to be retained ?

Can you tell me an example that needs to be kept?

This is because the auto-release pool has no time to consume its contents. This is an example of a crash:

< /p>

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

In your example, the auto-release pool that saves the string belongs to 99% of the current runloop. It creates a new pool at the beginning of the event loop, and then Drain it at the end.

Leave a Comment

Your email address will not be published.