IOS在子線程中使用定時器,將定時器添加至RunLoop中

  • (BOOL)application:(UIApplication )application didFinishLaunchingWithOptions:(NSDictionary )launchOptions
    {
    self.window = [[[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]] autorelease];

    //用NSObject的方法創建一個多線程
    [self performSelectorInBackground:@selector(multiThread) withObject:nil];

    self.window.backgroundColor = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    return YES;
    }

  • (void)multiThread
    {
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    if (![NSThread isMainThread]) {

    // 第1種方式
    //此種方式創建的timer已經添加至runloop中
    

    // [NSTimer scheduledTimerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    //保持線程爲活動狀態,才能保證定時器執行
    // [[NSRunLoop currentRunLoop] run];//已經將nstimer添加到NSRunloop中了

    //第2種方式
    //此種方式創建的timer沒有添加至runloop中
    

    NSTimer *timer = [NSTimer timerWithTimeInterval:1.0f target:self selector:@selector(timerAction) userInfo:nil repeats:YES];
    //將定時器添加到runloop中
    [[NSRunLoop currentRunLoop] addTimer:timer forMode:NSDefaultRunLoopMode];
    [[NSRunLoop currentRunLoop] run];
    NSLog(@”多線程結束”);
    }
    [pool release];
    }

  • (void)timerAction
    {
    //定時器也是在子線程中執行的
    if (![NSThread isMainThread]) {
    NSLog(@”定時器”);
    }
    }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章