开发者

Objective-C Threading: Exiting a thread, retain problems

I'm trying to create a thread that configures a run loop to run a physics engine through a defined NSTimer. However, I'm having trouble making the thread exit normally (or I think the problem is).

Attached are the relevant portions of my code:

(This code is in a view controller) (back is called when a button is pressed)

- (void)back {

    [timestep invalidate];
    exiting = YES;

    [self release];

}

- (void)initializePhysicsWorld {

    // Initializes the thread to simulate physics interactions.
    [NSThread detachNewThreadSelector:@selector(physicsThreadMethod)
                             toTarget:self
                           withObject:nil];
}

- (void)physicsThreadMethod {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];

    NSRunLoop *myRunLoop = [NSRunLoop currentRunLoop];

    timestep = [NSTimer timerWithTimeInterval:1.0f/60.0f
                                       target:self
                                     selector:@selector(step:)
                                     userInfo:nil
                                      repeats:YES];

    [myRunLoop addTimer:timestep forMode:NSDefaultRunLoopMode];

    while (!exiting) {

        CFRunLoopRun();

        [pool release];
        pool = [[NSAutoreleasePool alloc] init]; // periodically refreshes pool
    }
    CFRunLoopStop([myRunLoop getCFRunLoop]);
    NSLog(@"Thread is going to exit");
    [pool release];

}

- (void)dealloc {
    if ([self.view superview]) {
        [self.view removeFromSuperview];
    }

    [super dealloc];
}

The engine (the step: function) runs fine, but when I try to exit the loop by running the method back, it would appear that the thread does not release its retain on my view controller (dealloc is not called). I think my thread didn't exit the physicsThreadMethod method as the NSLog does not appear in the console. Dealloc was only called when I run 'back' a second time.

I'm not really sure why this is happeni开发者_运维百科ng, so I would really appreciate any help. Thanks!


The problem lies in here:

while (!exiting) {

    CFRunLoopRun(); //<-- here you start the run loop.
    // the lines under this line are NEVER executed. also the while loop does nothing
    [pool release];
    pool = [[NSAutoreleasePool alloc] init]; // periodically refreshes pool
}

You could use NSOperations to wrap your work, there are already properties defined on this class to do exactly this kind of thing.

If you want to stick with your implementation in a NSThread you have to take a look at the CFRunLoop reference and how to add observers to the run loop.


Does CFRunLoopRun return every step:? CFRunLoopStop or [myRunLoop runUntilDate:] would help.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜