LoginSignup
63
62

More than 5 years have passed since last update.

[Objective-C] デリゲート(Delegate)とは

Last updated at Posted at 2013-11-04

概要

あるクラスだけでは処理できない命令を、そのクラスの変わりに行うクラス(に引き渡すこと)。

  • どのクラスもデリゲート(代理人)になることができる。

デリゲートの手順

  1. UIパーツとデリゲート(先のクラス)を接続する
  2. デリゲート(先のクラス)にプロトコル名を書く
  3. デリゲート(先のクラス)に処理を書く

Sample

StoryBoardを使って、検索バー(UISearchBar)の処理をViewControllerにデリゲートしてみる。

※UISearchBarは「ユーザがタップした際にキーボードを表示する機能」や
「入力された文字列を自身の上に表示する機能」が用意されているが、
「入力された文字列をどのように扱うか」などは追加で(デリゲートして)実装する必要がある。

UIパーツとデリゲート(先のクラス)を接続する

StoryBoard上で、処理をデリゲートに依頼するUIパーツ(今回はUISearchBar)を右クリックし、
delegateプロパティをViewControllerクラスにドラッグし接続する。

デリゲート(先のクラス)にプロトコル名を書く

デリゲートされる側のヘッダファイル(今回はViewController.h)上で
「UISearchBarクラスの代理人であること」を宣言する。

@interface VIewController : UIViewController <UISearchBarDelegate>

(UISearchBarDelegateというプロトコルを宣言)

デリゲート(先のクラス)に処理を書く

処理を書く場所はプロトコルによって定められている。
今回の例のようにSearchBarのデリゲートになった場合は、
searchBarSearchButtonClicked:メソッド内に処理を書く。

-(void)searchBarSearchButtonClicked:(UISearchBar *)searchBar
{
    //デリゲート側で行う処理
}

参考

iPhoneアプリ開発超入門
http://www.sbcr.jp/products/4797369434.html

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