5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

もちろん俺らは抵抗するで?技術で🤜🤛Advent Calendar 2017

Day 24

segue遷移時の値受け渡しを便利にするで🤜🤛

Last updated at Posted at 2017-12-24

まだObjective-Cなんかやってんのかよーという声も聞こえてきそうですが、
Objective-CでSegueを使って遷移する時に超便利なカテゴリーを今回は紹介します!

UIViewController+SegueBlock.h
#import <UIKit/UIKit.h>

typedef void (^SegueBlock) (UIStoryboardSegue *segue);


@interface UIViewController (SegueBlock)

- (void)performSegueWithIdentifier:(NSString *)segue sender:(id)sender block:(SegueBlock)block;

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender NS_REQUIRES_SUPER;

@end

UIViewController+SegueBlock.m
#import "UIViewController+SegueBlock.h"
#import <objc/runtime.h>


@implementation UIViewController (SegueBlock)

- (void)performSegueWithIdentifier:(NSString *)segue sender:(id)sender block:(SegueBlock)block
{
    objc_setAssociatedObject(self, _cmd, block, OBJC_ASSOCIATION_RETAIN);
    [self performSegueWithIdentifier:segue sender:sender];
}

#pragma clang diagnostic push
#pragma clang diagnostic ignored "-Wobjc-protocol-method-implementation"
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender NS_REQUIRES_SUPER

{
    if ([self segueBlock]) {
        [self segueBlock] (segue);
    }
    
    objc_setAssociatedObject(self, @selector(performSegueWithIdentifier:sender:block:), nil, OBJC_ASSOCIATION_RETAIN);
}
#pragma clang diagnostic pop

- (SegueBlock)segueBlock
{
    return objc_getAssociatedObject(self, @selector(performSegueWithIdentifier:sender:block:));
}

@end

使用例

ViewController.m
- (IBAction)showSecondViewControllerButton:(UIButton *)sender {
    [self performSegueWithIdentifier:@"showSecondViewControler" sender:nil block:^(UIStoryboardSegue *segue) {
        SecondViewController *secondViewController =segue.destinationViewController;
        secondViewController.labelText = @"segueのブロックで値渡し";
    }];
}

// 以下のメソッドを実装する場合は Super でメソッドを呼ぶ
//- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
//{
//    [super prepareForSegue:segue sender:sender];
//}

@end

ブロックでdestinationViewControllerを取得できるので
次のViewControllerに値やオブジェクトを渡す時にかなり便利になります!

Githubにソースコードを上げてます。
SegueSample-GitHub

5
3
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
5
3

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?