Keep an NSThread containing an NSTimer around indefinitely? (iPhone)

跟風遠走 提交于 2019-12-05 07:24:10

问题


I have some web service data in my app that needs to be updated every 3 minutes. I had tried out a few approaches but got a really good piece of advise in here last week, I should not build a new thread every 3 minutes and then subsequently try and dealloc and synchronize all the different parts so that I avoided memory bug. Instead I should have a "worker thread" that was always running, but only did actual work when I asked it too (every 3 minutes).

As my small POC works now, I spawn a new thread in the applicationDidFinishLaunching method. I do this like so:

[NSThread detachNewThreadSelector:@selector(updateModel) toTarget:self withObject:nil];

- (void) updateModel {

    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    BackgroundUpdate *update = [[BackgroundUpdate alloc] initWithTimerInterval:180];
    [update release];
    [pool release];
}

Ok, this inits the "BackgroundUpdate" object with the update interval in seconds. Inside the updater it is simply like this for now:

@implementation BackgroundUpdate

- (id) initWithTimerInterval:(NSInteger) secondsBetweenUpdates {

    if(self = [super init]) {

        [NSTimer scheduledTimerWithTimeInterval:secondsBetweenUpdates 
                                        target:self 
                                        selector:@selector(testIfUpdateNeeded) 
                                        userInfo:nil 
                                        repeats:YES];
    }

    return self;
}

- (void) testIfUpdateNeeded {

    NSLog(@"Im contemplating an update...");

}

I have never used threads like this before. I has always been "setup autoReleasePool, do work, get your autoReleasePool drained, and goodbye".

My problem is that as soon as the initWithTimerInterval has run, the NSThread is done, it therefore returns to the updateModel method and has its pool drained. I guess it has to do with the NSTimer having it's own thread/runloop? I would like for the thread to keep having the testIfUpdateNeeded method run every 3 minutes.

So how will I keep this NSThread alive for the entire duration of my app?

Thank You for any help/advice given:)


回答1:


You're close. All you need to do now is start the run loop running so the thread doesn't exit and the timer runs. After your call to initWithTimerInterval:, just call

[[NSRunLoop currentRunLoop] run];

The thread will run its run loop indefinitely and your timer will work.




回答2:


It sounds like you might want an NSOperation instead of an old fashion thread. You could active the operation via a universal timer then it would execute on its own thread and then clean up its own memory when done.



来源:https://stackoverflow.com/questions/2318280/keep-an-nsthread-containing-an-nstimer-around-indefinitely-iphone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!