代码之家  ›  专栏  ›  技术社区  ›  RickiG

无限期地保持包含nstimer的nsthread?(iPhone)

  •  1
  • RickiG  · 技术社区  · 15 年前

    我的应用程序中有一些Web服务数据需要每3分钟更新一次。 我尝试了一些方法,但是上周在这里得到了一个非常好的建议,我不应该每3分钟构建一个新线程,然后尝试解除锁定并同步所有不同的部分,这样我就避免了内存错误。相反,我应该有一个一直在运行的“工作线程”,但只有在我提出要求时(每3分钟)才做实际工作。

    当我的小型POC工作时,我在 applicationDidFinishLaunching 方法。我是这样做的:

    [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];
    }
    

    好的,这会以秒为单位初始化“backgroundupdate”对象。在更新程序中,现在只是这样:

    @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...");
    
    }
    

    我以前从未用过这样的线。我一直在“建立自动租赁池,做工作,让你的自动租赁池排水,再见”。

    我的问题是一旦 initWithTimerInterval 已经运行了 NSThread 完成后,它将返回到updateModel方法并将其池排出。我想这和nstimer有自己的线程/runloop有关吧?我想让线继续 testIfUpdateNeeded 方法每3分钟运行一次。

    那么,在我的应用程序的整个过程中,我如何保持这个nsthread的活动状态呢?

    感谢您提供的任何帮助/建议:)

    2 回复  |  直到 15 年前
        1
  •  5
  •   Ken Aspeslagh    15 年前

    你离我很近。现在您需要做的就是启动运行循环,这样线程就不会退出,计时器也会运行。在调用initWithTimerInterval:之后,只需调用

    [[NSRunLoop currentRunLoop] run];
    

    线程将无限期地运行其运行循环,计时器将工作。

        2
  •  0
  •   TechZen    15 年前

    听起来你可能想要一个 NSOperation 而不是旧的时尚线。您可以通过通用计时器激活该操作,然后它将在自己的线程上执行,然后在完成后清理自己的内存。