LoginSignup
10
9

More than 5 years have passed since last update.

delegateするまでもない場合のBlocksの利用

Last updated at Posted at 2013-03-12

モーダルで表示した画面とのやり取りで、一個の値だけ取り出してDismissするだけのために独自にDelegate作成するの嫌だよなーというときにBlocksというか関数ポインタというか的な感じで手抜きをしちゃう場合です。

どこかのタイミングで、
[self performSegueWithIdentifier:@"SegueName" sender:self];
あるいは、単純にInterfaceBuilder上からボタンなどに連携させても良い

モーダル画面の親側(実装:.m)
    if([segId isEqualToString:@"SegueName"]) {
        [[segue destinationViewController] setFunc:^(NSString * n) {
            NSLog(@"%s nickname=%@",__FUNCTION__,n);
                       // nを煮るなり焼くなりしてください。
            [self dismissModalViewControllerAnimated:YES];
        }];

    }

表示する側の実装もしたくなけど、これは手を抜けないっぽい。
例えば、テキストに文字を入力してもらうだけとかの場合、UIViewControllerにTextFieldを一つ貼付ける。

モーダル画面(定義:.h)側
 typedef void (^SetTextFunc) (NSString *);
 @interface MyViewContoller : UIViewController
 @property (nonatomic, copy) SetTextFunc func;
 @end

funcがポイントですかね。ちなみに、ARC前提です。

モーダル画面(実装:.m)側
@interface MyViewContoller()
{
    __weak IBOutlet UITextField *txt;     // 貼付けたTextField
}
@end
@implementation MyViewContoller
- (IBAction)onClose:(id)sender                 // 確定ボタンとかが押された時に呼ぶ
{
    if (_func==nil) return;
    _func(txt.text);
}

@end

もう少しスッキリさせたいところですが。。。

10
9
0

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
10
9