开发者

iphone: threads + release pool + [ object release] = "message sent to deallocated instance"

I'm having a bad time with some little code running on the iphone.

Basically, i just press a button, it calls runTest, it runs test method on a background thread. That's why I created an autorelease pool.

if i run the below code i got a beautiful message on the console saying:

2010-09-07 11:45:15.527 test[1312:207] *** -[CFString release]:开发者_如何学JAVA message sent to deallocated instance 0x3d52ba0

-(void) test {
    NSAutoreleasePool *apool = [[NSAutoreleasePool alloc] init];

    NSString *xml = [[NSString alloc] initWithFormat:@"<%@>", @"msg"];
    NSLog(@"%@\n",xml);
    [xml release];

    [apool release]; // <-- this line throws the error msg  
}

- (IBAction) runTest: (id)sender
{
    [self performSelectorInBackground:@selector(test) withObject:nil];

}

I have found that: if I do not run test on a background thread (no autorelease pool), just calling [self test], the code works fine.

So, i think the problem is around the thread + autorelease pool, what am I doing wrong? and how may I solve it?

P.S. I have the NSZombie flag enabled.


NSLog may have to send a message to the UI thread (perform selector on main thread) to print serialized to the console, by which time, your xml is already released.


It shouldn't matter in this case, but you should always drain pools and never release them.

That is a truly bizarre error, if that is all the code.

The first thing I'd suggest is running the code with zombie detection enabled while recording all retain/release events in Instruments. That'll give you an inventory of retain/releases on the offending object. Post the results if it still doesn't make sense.


Have you tried -autorelease on the object xml instead? This will add it to the active pool, apool. Declaring drain is better than declaring -release - they're the same in a non-garbage collection environment, but some day Apple may implement garbage collection on the iPhone. Hope this helps.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜