LoginSignup
13
13

More than 5 years have passed since last update.

遅延処理を簡潔に!Blocksの中に書いた処理を遅延実行するカテゴリ

Last updated at Posted at 2014-01-25

普通に特定のメソッドを遅延実行する場合はNSObjectクラスの「performSelector:withObject:afterDelay:」メソッドを使用しますが、簡単な処理だとわざわざメソッドを定義するのは面倒だし、可読性が落ちます。
そこで、今回はそれを特定のメソッドではなく、Blocksの内容を遅延実行するカテゴリをご紹介します!

NSObject+BlocksWait

NSObject+BlocksWait.h
#import <Foundation/Foundation.h>

@interface NSObject (BlocksWait)

+ (void)performBlock:(void(^)())block afterDelay:(NSTimeInterval)delay;

@end
NSObject+BlocksWait.m
#import "NSObject+BlocksWait.h"

@implementation NSObject (BlocksWait)


+ (void)performBlock:(void(^)())block afterDelay:(NSTimeInterval)delay 
{
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delay * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), block);
}

@end

使用例

最近リリースした「キス顔カメラ - 気になるあの子のキス顔が撮れるアプリ」では以下のように、1.5秒後に音声を再生する、のような処理を行うときに使用しています。

hoge.m
#import "NSObject-BlocksWait.h"


- (void)hogehoge
{
    // …いろいろ処理があって…


    [NSObject performBlock:^{
        NSString *soundPath = [[NSBundle mainBundle] pathForResource:@"foo" ofType:@"wav"];
        self.player = [[AVAudioPlayer alloc] initWithContentsOfURL:[NSURL fileURLWithPath:soundPath] error:nil];
        [self.player play];
    } afterDelay:1.5f];

    // …いろいろ処理があって…
}
13
13
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
13
13