开发者

Why isn’t my object collected by an autorelease pool?

I wrote an simple demo

@im开发者_JS百科plementation A

- (void)a{
    NSLog(@"%@",url);
}

-(id)init{
    self = [super init];
    url = [NSURL URLWithString:@"http://xxx.com"];
    return self;
}
@end

A *a = [A new];
while (YES) {
    [NSThread sleepForTimeInterval:0.5];
    [a a];  
}

but seems it will keep running and never crash. so when will an autorelease object be releaed?


No run-loop processing is done while the thread sleeps, so that the main run loop never runs during your endless while-loop and autoreleased objects are not collected by the default pool. If you spin the run loop, your code should crash just fine:

[[NSRunLoop mainRunLoop] runUntilDate:[NSDate dateWithTimeIntervalSinceNow:0.1]];

But it might be the case that the simple NSLog will work even though the object was released. Enabling zombies should do the trick for sure (provided that you spin the run loop).


What do you expect to happen?

You only have one NSURL instance floating about.

The implementation details of NSLog() are just that; implementation details. It is equally as likely that NSLog() creates its own autorelease pool as it is that NSLog() special cases "%@" such that it just logs the description of the passed object; nothing allocated in the pool.

How are you determining whether or not a crash should happen in the first place? Given a 1/2 second pause, even if it were to allocate 128 bytes per pass, you'd be looking at -- what -- a few years, nearly a decade?, before it allocates 2GB of memory?

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜