LoginSignup
7
7

More than 5 years have passed since last update.

自前のDelegateを実装する!!

Posted at

はじめに

iOS開発を学びはじめた頃に、TableView使うときにtableView.delegate = selfってやってるけど、
やらないと使えないのはわかるけど一体どうなってるんだ?と思いませんでしたか?(僕は思ってました。。。)
自分で実装してみるのが一番だ!まずは手を動かそう!な僕は実装してみて初めて少しだけ理解が深まった気がしたので、備忘録とiOS開発を始めたばかりの人への手助けを兼ねて筆をとりました。

Delegateって?

デリゲートパターン(処理の委譲)
あるクラス(A)の処理をあるクラス(B)に任せるという事になります。
TableViewCellに配置したボタンが押されたらViewControllerで画面遷移を行う実装をしたい時などに使います。(いい例が思い浮かびませんでした。。。)
では上記の実装を仮定として進めていきたい思います!

1.プロトコルの定義

CustomTableViewCell.h
#import <UIKit/UIKit.h>;

@protocol CustomCellDeleagete <NSObject>

@end

2.デリゲートメソッドの定義

CustomTableViewCell.h
#import <UIKit/UIKit.h>;

@protocol CustomCellDeleagete <NSObject>

@optional
/**
* ボタンがタップされた時に呼び出されるデリゲートメソッド
*/
- (void) buttonTapped;
@end

デリゲートメソッドにはrequiredとoptional修飾子があり、
requiredは実装必須のメソッド
optionalは任意で実装のメソッドとなります。
設定しない場合はデフォルトでoptionalとなります。

3.デリゲートインスタンスを定義

CustomTableViewCell.h
#import <UIKit/UIKit.h>;

@protocol CustomCellDeleagete <NSObject>

@optional
/**
* ボタンがタップされた時に呼び出されるデリゲートメソッド
*/
- (void) buttonTapped;
@end

/**
* CustomCellDelegateインスタンス
*/
@property (nonatomic, weak) id<CustomCellDelegate> delegate;

weak参照とid型のプロパティとして保持します。

4.デリゲートの呼び出しを実装

CustomTableViewCell.m
@implementation CustomTableViewCell
// 処理諸々は省略

#pragma mark - IBAction

// ボタン押下で呼び出し
- (IBAction) didTapBtn:(id)Sender {
    // デリゲートインスタンスがメソッドを実装しているかチェック
    if ([self.delegate respondsToSelector:@selector(buttonTapped)]) {
        // 実装されていれば、デリゲートインスタンスへ処理を委譲
        [self.delegate buttonTapped];
    }
}

@end

buttonTappedの処理は委譲先のクラスで実装します。

5.プロトコルを準拠する

ViewController.m
#import ViewController.h

@interface ViewController () <CustomCellDelegate>

@end

6.デリゲートインスンタンスにselfをセット

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    // cellIdentifierは仮
    static NSString *cellIdentifier = @"Cell";
    CustomTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    // delegateインスタンスにselfをセット
    cell.delegate = self;
    return cell
}

7.デリゲートメソッドの処理実装

ViewController.m
@implementation ViewController
// 省略
- (Void) buttonTapped {
    // 画面遷移処理
    [self.navigationController pushViewController:nextView animated:YES];
}

終わりに

Delegateの実装は以上になります。
実装の過程を見ることで、TableView等のdelegateの仕組みの理解の手助けになれば幸いです。
iOS開発をしていると、Delegateを使って処理を委譲させたいシーンは必ず出てくるので、Delegateの実装は必須の知識になると思います。
コピーアンドペーストではなく、理解した上で実装を行えるようになりたいですね!

7
7
4

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