iOSアプリ開発の逆引き辞典

iPhone/iPadで使えるアプリ開発のTipsをまとめてみました

NSTimerでblocksを処理する

NSTimerのカテゴリを扱ったプロジェクトは沢山ありますが、その中でも「NSTimer-Blocks」が使いやすくて重宝しています。

実際に使う際には、下記のように使用します。下記のサンプルコードはUITableViewのセルをタップして、3秒後にtimerTickedのblocksを処理します。

#import "NSTimer+Blocks.h"

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    void (^timerTicked)() = ^{
        UIAlertView* alert = nil;
        alert = [[UIAlertView alloc] initWithTitle:@"タイマー"
            message:@"満了"
            delegate:nil
            cancelButtonTitle:@"閉じる"
            otherButtonTitles:nil];
        [alert show];
    };

    [NSTimer scheduledTimerWithTimeInterval:3.f 
        block:timerTicked repeats:NO];
}