SlideShare uma empresa Scribd logo
1 de 22
Baixar para ler offline
iOSハンズオントレーニング
Delegate(委譲)、Notification(通知)、KVO(キー値監視)

 大久保 聡
目次
Observerパターン

Delegate(委譲)

Notification(通知)

KVO : Key-Value Observing(キー値監視)
Observerパターン
Observerパターンに登場するのは、2つのクラスだ。
監視するクラスと、監視されて通知を行うクラスだ。
監視するクラスの方を、Observerクラスと呼ぼう。
もう一方の監視されるクラスの方は、Subjectクラ
スとする。
Delegate(委譲)
委譲元オブジェクトのポインタを移譲先オブジェクトで
保持し、委譲先オブジェクトから委譲元オブジェクトの
メソッドをコールする。・・・コールバック
Delegate実装
(実装イメージ)
アルバムに写真を配置、写真がタップされ
たらその選ばれた写真の処理をしたい。
監視側のObserverクラス

監視される側のSubject

をUIView

クラスをUIImageView

タップされた
ら親クラスの
メソッドをコー
ルバックする。
Delegate実装
(Subjectクラスの作成)
UIImageViewクラスを新たに作成する。

UIImageViewクラスに、Observerクラスのポインタを
保持するメンバ変数を追加する。

ユーザ操作を受け付けるように変更する。
self.userInteractionEnabled = YES;

タップされたら、Observerクラスのメソッドをコール
する。
※ベースとなるプロジェクトをダウンロードしてください。

https:/
/github.com/ovjang/NoUseStoryBoard_Observer
//
//
//

PictureView.h

!
#import <UIKit/UIKit.h>
!

@interface PictureView : UIImageView
{
@private
NSObject *delegate_;
}

!
@property NSObject *delegate;
!
@end
//
//
//

PictureView.m

!
#import "PictureView.h"
!

@implementation PictureView
@synthesize delegate = delegate_;

!

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.userInteractionEnabled = YES; // UIImageViewはデフォルトでNoなので注意
}
return self;
}

!

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if(delegate_ !=nil) {
[delegate_ pictureSelected];
}
}

!

@end
Delegate実装
(プロトコルの作成)
プロトコルを新たに作成する。

subjectクラスのメンバ変数に、プロトコルを指定
する。

タップされた際に呼ぶメソッドで、プロトコルに
準拠していることを確認する。
//
//

PictureViewDelegate.h (javaでいうところのインターフェース)

//

!
#import <Foundation/Foundation.h>
!

@protocol PictureViewDelegate <NSObject>
@optional
-(void)pictureSelected; // 抽象メソッド

!

@end
//
//
//

PictureView.h

!

#import <UIKit/UIKit.h>
#import "PictureViewDelegate.h"

!

@interface PictureView : UIImageView
{
@private
NSObject <PictureViewDelegate> *delegate_;
}
@property NSObject <PictureViewDelegate> *delegate;
@end
//
//
//

PictureView.m

!
#import "PictureView.h"
!

@implementation PictureView
@synthesize delegate = delegate_;

!

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.userInteractionEnabled = YES;
}
return self;
}

!

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
if(delegate_ !=nil) {
if ([delegate_ conformsToProtocol:@protocol(PictureViewDelegate)]) {
if ([delegate_ respondsToSelector:@selector(pictureSelected)]) {
[delegate_ pictureSelected];
}
}
}
}
@end
Delegate実装
(Observerクラスの作成)
既存のUIViewControllerを、Observerクラスにしま
す。また、プロトコルに準拠させる。

Subjectクラスを、newして画面に配置する。

Subjectクラスのメンバ変数に、自分のポインタを格納
する。

プロトコルにあるメソッドを実装する。
//

Screen1ViewController.h

!

#import <UIKit/UIKit.h>
#import "PictureViewDelegate.h"

!
@interface Screen1ViewController : UIViewController <PictureViewDelegate>
!
@end

/

!

Screen1ViewController.m

#import "Screen1ViewController.h"
#import "PictureView.h"

!
@interface Screen1ViewController ()
!
@end
!
@implementation Screen1ViewController
!

- (id)init
{
self = [super init];
if (self) {
// Custom initialization
self.title = @"Album";
self.view.backgroundColor = [UIColor grayColor];
}
return self;
}

!

- (void)viewDidLoad
{
[super viewDidLoad];
UIImage* image01 = [UIImage imageNamed:@"picture01.jpeg"];
PictureView* uiImageView1 = [[PictureView alloc]
initWithFrame:CGRectMake(10, 10, 100, 150)];
uiImageView1.delegate = self;
uiImageView1.image = image01;
[self.view addSubview:uiImageView1];

!

UIImage* image02 = [UIImage imageNamed:@"picture02.jpeg"];
PictureView* uiImageView2 = [[PictureView alloc]
initWithFrame:CGRectMake(120, 10, 100, 150)];
uiImageView2.delegate = self;
uiImageView2.image = image02;
[self.view addSubview:uiImageView2];

}

!

-(void)pictureSelected {
NSLog(@"Push");
}

!

@end
Notification(通知)
仲介役がObserverクラスと、Subjectクラ
スのひも付けと連絡を行う。
OK
Tapって通知があったら教えてね

Observer

クラス

Subject

クラス

NSnotificationCenter

addObserver

通知があったら、これを

コールバックしてね

Observer

クラス

!!
Tapって通知を送る

NSnotificationCenter

postNotification

Subject

クラス

通知あった
Tapって通知をあったよ!!

Observer

クラス

NSnotificationCenter
コールバック

Subject

クラス
Notification実装
(NotificationCenterにObserber登録)
NSNotificationCenterを取得する。
Observerを登録する。知らせて欲しい通知と、知らせ
る際に呼び出してもらうセレクターを指定する。(この
娘の返事だけ、教えてねということもできます。)
//
//
//

Screen1ViewController.m

!

#import "Screen1ViewController.h"
#import "PictureView.h"

!
@interface Screen1ViewController ()
!
@end
!
@implementation Screen1ViewController
!

- (id)init
{
self = [super init];
if (self) {
// Custom initialization
self.title = @"Album";
self.view.backgroundColor = [UIColor grayColor];
// NSNotificationCenterを取得する
NSNotificationCenter* center;
center = [NSNotificationCenter defaultCenter];
// Observerとして登録する
[center addObserver:self selector:@selector(pictureSelected:)
name:@"PictureTaped" object:nil];
}
return self;
}
Notification実装
(通知を送る)
NSNotificationCenterを取得する。
送る通知(NSNotification)を作成する。
NSNotificationCenterに、通知を送る。
//
//
//

PictureView.m

!
#import "PictureView.h"
!
@implementation PictureView
!

- (id)initWithFrame:(CGRect)frame
{
self = [super initWithFrame:frame];
if (self) {
// Initialization code
self.userInteractionEnabled = YES;
}
return self;
}

!

- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event {
// NSNotificationを作成する
NSNotification* notification;
notification = [NSNotification notificationWithName:@"PictureTaped"
object:self userInfo:nil];
// NSNotificationCenterを取得する
NSNotificationCenter* center;
center = [NSNotificationCenter defaultCenter];
// 通知を行う
[center postNotification:notification];
}

!

@end

//
//
//

PictureViewDelegate.h

!
#import <Foundation/Foundation.h>
!

@protocol PictureViewDelegate <NSObject>
@optional
-(void)pictureSelected:(NSNotification *)notification;

!

@end
Notification実装
(通知を受け取る)
コールバックされてくるメソッドで、通知
(NSNotification)を受け取る。
NSNotificationに含まれる情報、
UserInfo(NSDictionary)の中身をもとに必要な
処理を行う。
//
//
//

Screen1ViewController.m

!

#import "Screen1ViewController.h"
#import "PictureView.h"

!
@interface Screen1ViewController ()
!
@end
!
@implementation Screen1ViewController
!

- (id)init
{
self = [super init];
if (self) {
// Custom initialization
self.title = @"Album";
self.view.backgroundColor = [UIColor grayColor];
// NSNotificationCenterを取得する
NSNotificationCenter* center;
center = [NSNotificationCenter defaultCenter];
// Observerとして登録する
[center addObserver:self selector:@selector(pictureSelected:)
name:@"PictureTaped" object:nil];
}
return self;
}

!

- (void)viewDidLoad
{
[super viewDidLoad];
UIImage* image01 = [UIImage imageNamed:@"picture01.jpeg"];
PictureView* uiImageView1 = [[PictureView alloc]
initWithFrame:CGRectMake(10, 10, 100, 150)];
uiImageView1.image = image01;
uiImageView1.tag = 1;
[self.view addSubview:uiImageView1];

!

UIImage* image02 = [UIImage imageNamed:@"picture02.jpeg"];
PictureView* uiImageView2 = [[PictureView alloc]
initWithFrame:CGRectMake(120, 10, 100, 150)];
uiImageView2.image = image02;
uiImageView2.tag = 2;
[self.view addSubview:uiImageView2];

}

!

-(void)pictureSelected:(NSNotification*)notification {
NSLog(@"Push %@",notification.userInfo);
}

!

@end
KVO(キー値監視)
キー値監視とは、ほかのオブジェクトに属する特定の
プロパティの変化について通知をオブジェクトが受け
取れるようにする仕組みです。(キー値監視に必要な
メソッドは、ルートクラスであるNSObjectに実装さ
れている。)
KVO実装
(Subjectクラス)
監視する値を持つクラスを作成する。
//
//
//

KVOclass.h

!
#import <Foundation/Foundation.h>
!
@interface KVOclass : NSObject
{
int value_;
}
@property int value;

!

@end

//
//
//

KVOclass.m

!
#import "KVOclass.h"
!

@implementation KVOclass
@synthesize value = value_;

!

@end
KVO実装
(Subjectクラス)
Subjectクラスにオブザーバーを追加する。
OBserverクラスに、変更通知を受け取るメソッド
を、オーバーライドする。
//
//
//

Screen1ViewController.m

!

#import "Screen1ViewController.h"
#import "KVOclass.h"
@interface Screen1ViewController ()

!
@end
!
@implementation Screen1ViewController
!

- (id)init
{
self = [super init];
if (self) {
// Custom initialization
self.title = @"KVO Test";
self.view.backgroundColor = [UIColor grayColor];
}
return self;
}

!

- (void)viewDidLoad
{
[super viewDidLoad];

!
!

KVOclass* kvo01 = [KVOclass new];
[kvo01 addObserver:self forKeyPath:@"value" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
KVOclass* kvo02 = [KVOclass new];
[kvo02 addObserver:self forKeyPath:@"value" options:(NSKeyValueObservingOptionNew|NSKeyValueObservingOptionOld) context:nil];
kvo01.value = 1; // 値を変更

}

!

- (void)observeValueForKeyPath:(NSString*)keyPath
ofObject:(id)object
change:(NSDictionary*)change
context:(void*)context
{
if ([keyPath isEqual:@"value"])
{
NSLog(@"New Key = %@",[change objectForKey:NSKeyValueChangeNewKey]);
}
}

!

@end

Mais conteúdo relacionado

Destaque

Destaque (6)

AppLovin高収益の秘密に迫る!アドフリくんマネタイズナイト_201511118
AppLovin高収益の秘密に迫る!アドフリくんマネタイズナイト_201511118AppLovin高収益の秘密に迫る!アドフリくんマネタイズナイト_201511118
AppLovin高収益の秘密に迫る!アドフリくんマネタイズナイト_201511118
 
SDK不要で高パフォーマンス!AppLovinのネイティブ広告_20160427
SDK不要で高パフォーマンス!AppLovinのネイティブ広告_20160427SDK不要で高パフォーマンス!AppLovinのネイティブ広告_20160427
SDK不要で高パフォーマンス!AppLovinのネイティブ広告_20160427
 
収益最大化には欠かせない!動画リワードxメディエーション at Vungle勉強会 #applovin
収益最大化には欠かせない!動画リワードxメディエーション at Vungle勉強会 #applovin収益最大化には欠かせない!動画リワードxメディエーション at Vungle勉強会 #applovin
収益最大化には欠かせない!動画リワードxメディエーション at Vungle勉強会 #applovin
 
AWS Black Belt Techシリーズ AWS SDK
AWS Black Belt Techシリーズ AWS SDKAWS Black Belt Techシリーズ AWS SDK
AWS Black Belt Techシリーズ AWS SDK
 
Mobile SDK: Considerations & Best Practices
Mobile SDK: Considerations & Best Practices Mobile SDK: Considerations & Best Practices
Mobile SDK: Considerations & Best Practices
 
iOS/Androidアプリエンジニアが理解すべき「Model」の振る舞い
iOS/Androidアプリエンジニアが理解すべき「Model」の振る舞いiOS/Androidアプリエンジニアが理解すべき「Model」の振る舞い
iOS/Androidアプリエンジニアが理解すべき「Model」の振る舞い
 

Mais de 聡 大久保

Mais de 聡 大久保 (20)

Oculus Interaction SDK で物をつかむ編
Oculus Interaction SDK で物をつかむ編Oculus Interaction SDK で物をつかむ編
Oculus Interaction SDK で物をつかむ編
 
Oculus Interaction SDK でグラブまわりの設定方法
Oculus Interaction SDK でグラブまわりの設定方法Oculus Interaction SDK でグラブまわりの設定方法
Oculus Interaction SDK でグラブまわりの設定方法
 
空間を認識する - 取り込みから表示まで -
空間を認識する - 取り込みから表示まで -空間を認識する - 取り込みから表示まで -
空間を認識する - 取り込みから表示まで -
 
Photon Fusionのはじめの一歩
Photon Fusionのはじめの一歩Photon Fusionのはじめの一歩
Photon Fusionのはじめの一歩
 
Hololens2 MRTK2.7(OpenXR) でのビルド環境構築(環境設定からビルドまで)
Hololens2 MRTK2.7(OpenXR) でのビルド環境構築(環境設定からビルドまで)Hololens2 MRTK2.7(OpenXR) でのビルド環境構築(環境設定からビルドまで)
Hololens2 MRTK2.7(OpenXR) でのビルド環境構築(環境設定からビルドまで)
 
Hololens2でアカウント情報の取得
Hololens2でアカウント情報の取得Hololens2でアカウント情報の取得
Hololens2でアカウント情報の取得
 
HoloLens2とPCで、WebRTCで映像をやりとり
HoloLens2とPCで、WebRTCで映像をやりとりHoloLens2とPCで、WebRTCで映像をやりとり
HoloLens2とPCで、WebRTCで映像をやりとり
 
UnityでVRアプリ(Android Cardboard)を作る -準備編-
UnityでVRアプリ(Android Cardboard)を作る -準備編-UnityでVRアプリ(Android Cardboard)を作る -準備編-
UnityでVRアプリ(Android Cardboard)を作る -準備編-
 
VRでのUI設計のヒント
VRでのUI設計のヒントVRでのUI設計のヒント
VRでのUI設計のヒント
 
ハードサーフェイスモデリング勉強会(Blender2.79b編)
ハードサーフェイスモデリング勉強会(Blender2.79b編)ハードサーフェイスモデリング勉強会(Blender2.79b編)
ハードサーフェイスモデリング勉強会(Blender2.79b編)
 
Google Tangoで 現実世界を感じてみよう
Google Tangoで現実世界を感じてみようGoogle Tangoで現実世界を感じてみよう
Google Tangoで 現実世界を感じてみよう
 
仮想マシンを仮想空間で見る Cloud roadshow
仮想マシンを仮想空間で見る Cloud roadshow仮想マシンを仮想空間で見る Cloud roadshow
仮想マシンを仮想空間で見る Cloud roadshow
 
AWSのEC2の複数インスタンスからファイルを共有する方法
AWSのEC2の複数インスタンスからファイルを共有する方法AWSのEC2の複数インスタンスからファイルを共有する方法
AWSのEC2の複数インスタンスからファイルを共有する方法
 
Awsで構築したのだよ 06 ec2インスタンス起動時にCloudWatchのアラームを追加する
Awsで構築したのだよ 06 ec2インスタンス起動時にCloudWatchのアラームを追加するAwsで構築したのだよ 06 ec2インスタンス起動時にCloudWatchのアラームを追加する
Awsで構築したのだよ 06 ec2インスタンス起動時にCloudWatchのアラームを追加する
 
Awsで構築したのだよ 05 プロセス監視、メモリ使用率、ディスク使用率をCloudWatchのカスタムメトリクスに追加したい
Awsで構築したのだよ 05 プロセス監視、メモリ使用率、ディスク使用率をCloudWatchのカスタムメトリクスに追加したいAwsで構築したのだよ 05 プロセス監視、メモリ使用率、ディスク使用率をCloudWatchのカスタムメトリクスに追加したい
Awsで構築したのだよ 05 プロセス監視、メモリ使用率、ディスク使用率をCloudWatchのカスタムメトリクスに追加したい
 
Awsで構築したのだよ 04 ec2インスタンス起動時にホスト名を変更
Awsで構築したのだよ 04 ec2インスタンス起動時にホスト名を変更Awsで構築したのだよ 04 ec2インスタンス起動時にホスト名を変更
Awsで構築したのだよ 04 ec2インスタンス起動時にホスト名を変更
 
Awsで構築したのだよ 03 ec2インスタンスに設定したタグをサーバから取得
Awsで構築したのだよ 03 ec2インスタンスに設定したタグをサーバから取得Awsで構築したのだよ 03 ec2インスタンスに設定したタグをサーバから取得
Awsで構築したのだよ 03 ec2インスタンスに設定したタグをサーバから取得
 
Awsで構築したのだよ 02 ec2インスタンスから自分のインスタンスidを取得
Awsで構築したのだよ 02 ec2インスタンスから自分のインスタンスidを取得Awsで構築したのだよ 02 ec2インスタンスから自分のインスタンスidを取得
Awsで構築したのだよ 02 ec2インスタンスから自分のインスタンスidを取得
 
Awsで構築したのだよ 01 ユーザのコンソール操作をログに残す
Awsで構築したのだよ 01 ユーザのコンソール操作をログに残すAwsで構築したのだよ 01 ユーザのコンソール操作をログに残す
Awsで構築したのだよ 01 ユーザのコンソール操作をログに残す
 
awsを学ぶ上で必要となる前提知識(DB)
awsを学ぶ上で必要となる前提知識(DB)awsを学ぶ上で必要となる前提知識(DB)
awsを学ぶ上で必要となる前提知識(DB)
 

Último

Último (12)

新人研修 後半 2024/04/26の勉強会で発表されたものです。
新人研修 後半        2024/04/26の勉強会で発表されたものです。新人研修 後半        2024/04/26の勉強会で発表されたものです。
新人研修 後半 2024/04/26の勉強会で発表されたものです。
 
知識ゼロの営業マンでもできた!超速で初心者を脱する、悪魔的学習ステップ3選.pptx
知識ゼロの営業マンでもできた!超速で初心者を脱する、悪魔的学習ステップ3選.pptx知識ゼロの営業マンでもできた!超速で初心者を脱する、悪魔的学習ステップ3選.pptx
知識ゼロの営業マンでもできた!超速で初心者を脱する、悪魔的学習ステップ3選.pptx
 
Utilizing Ballerina for Cloud Native Integrations
Utilizing Ballerina for Cloud Native IntegrationsUtilizing Ballerina for Cloud Native Integrations
Utilizing Ballerina for Cloud Native Integrations
 
LoRaWANスマート距離検出センサー DS20L カタログ LiDARデバイス
LoRaWANスマート距離検出センサー  DS20L  カタログ  LiDARデバイスLoRaWANスマート距離検出センサー  DS20L  カタログ  LiDARデバイス
LoRaWANスマート距離検出センサー DS20L カタログ LiDARデバイス
 
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアルLoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
LoRaWAN スマート距離検出デバイスDS20L日本語マニュアル
 
Observabilityは従来型の監視と何が違うのか(キンドリルジャパン社内勉強会:2022年10月27日発表)
Observabilityは従来型の監視と何が違うのか(キンドリルジャパン社内勉強会:2022年10月27日発表)Observabilityは従来型の監視と何が違うのか(キンドリルジャパン社内勉強会:2022年10月27日発表)
Observabilityは従来型の監視と何が違うのか(キンドリルジャパン社内勉強会:2022年10月27日発表)
 
論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games
論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games
論文紹介: The Surprising Effectiveness of PPO in Cooperative Multi-Agent Games
 
論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding
論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding
論文紹介:Selective Structured State-Spaces for Long-Form Video Understanding
 
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
NewSQLの可用性構成パターン(OCHaCafe Season 8 #4 発表資料)
 
論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...
論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...
論文紹介:Video-GroundingDINO: Towards Open-Vocabulary Spatio-Temporal Video Groun...
 
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その22024/04/26の勉強会で発表されたものです。
 
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
Amazon SES を勉強してみる その32024/04/26の勉強会で発表されたものです。
 

iOSハンズオントレーニング observer編 (delegate,notification,KVO)