iOS 向けにプログラミングしていると、次のような状況に直面することがよくあります。
- (void)someMethod
{
[self performSomeAnimation];
//below is an action I want to perform, but I want to perform it AFTER the animation
[self someAction];
}
- (void)performSomeAnimation
{
[UIView animateWithDuration:.5 animations:^
{
//some animation here
}];
}
このような状況に直面した場合、通常は次のように完了ブロック ハンドラーを使用できるように、アニメーション コードをコピー アンド ペーストするだけになります。
- (void)someMethod
{
[self performSomeAnimation];
//copy pasted animation... bleh
[UIView animateWithDuration:.5 animations:^
{
//same animation here... code duplication, bad.
}
completion^(BOOL finished)
{
[self someAction];
}];
}
- (void)performSomeAnimation
{
[UIView animateWithDuration:.5 animations:^
{
//some animation here
}];
}
この問題を解決する適切な方法は何ですか? 以下のようにコードのブロックをメソッドに渡し-(void)performSomeAction
、アニメーションの完了時にそのブロックを実行する必要がありますか?
- (void)someMethod
{
block_t animationCompletionBlock^{
[self someAction];
};
[self performSomeAnimation:animationCompletionBlock];
}
- (void)performSomeAnimation:(block_t)animationCompletionBlock
{
[UIView animateWithDuration:.5 animations:^
{
//some animation here
}
completion^(BOOL finished)
{
animationCompletionBlock();
}];
}
それはこの問題を解決する適切な方法ですか?私はブロックの使用法に精通しておらず(そのブロックを適切に宣言したかどうかさえわからない)、単純な問題に対する複雑な解決策のように見えるため、それを避けてきたと思います。