XCodeでアプリを作成していると,delegateメソッドを結構使います.
自分で作成したクラスでもdelegateが使えたら便利なのに…と思う事はあると思います.
そこで,簡単にdelegateを実装する手順を示します.
今回はMyDelegateSampleと言うクラスを作成し,ViewControllerから呼び出してdelegateを受け取ると言う想定です.
ソース中にコメントを埋め込んでいますので,解説は特に書きません.
MyDelegateSample.h
#import <Foundation/Foundation.h>
// Define Delegate
@protocol MyDelegateSampleDelegate <NSObject>
// Declare Delegate methods.
// Only declaration. Implements shoud be done by ViewController
- (void)sampleDelegate;
- (void)sampleDelegateWithParameter:(NSInteger)val;
@end
@interface MyDelegateSample : NSObject
// Define property so that it could be seen from user object
@property (nonatomic, assign) id<MyDelegateSampleDelegate> delegate;
// initializer
- (id)init;
// Method which calls delegate
- (void)fireDelegate;
- (void)fireDelegateWithParameter;
@end
MyDelegateSample.m
#import "MyDelegateSample.h"
@implementation MyDelegateSample
// Initializer Implement
- (id)init
{
if (self = [super init]) {
// Do initilaization if needed
}
return self;
}
// Fire delegates
- (void)fireDelegate
{
// check if user has implemeted the delegate method
if ([self.delegate respondsToSelector:@selector(sampleDelegate)])
{
// fire sampleDelegate
[_delegate sampleDelegate];
}
}
- (void)fireDelegateWithParameter
{
// check if user has implemeted the delegate method
if ([self.delegate respondsToSelector:@selector(sampleDelegateWithParameter:)])
{
// fire sampleDelegate
[_delegate sampleDelegateWithParameter:10];
}
}
@end
ViewController.h
#import <UIKit/UIKit.h>
#import "MyDelegateSample.h"
@interface ViewController : UIViewController<MyDelegateSampleDelegate>
@end
ViewController.m
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
// Create MyDelagateSample Instance
MyDelegateSample* myDelegate = [[MyDelegateSample alloc]init];
// Set myDelegate's delegate to self
myDelegate.delegate = self;
// Fire first sampleDelegate
[myDelegate fireDelegate];
// Fire second sampleDelegateWithParameter
[myDelegate fireDelegateWithParameter];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
// Implemets Delegate Methods
- (void)sampleDelegate
{
NSLog(@"sampleDelegate is fired");
}
- (void)sampleDelegateWithParameter:(NSInteger)val
{
NSLog(@"sampleDelegateWithParameter is fired with value %ld", (long)val);
}
@end
Single View Applicationを作成して,上記のコードを書いてシミュレーターで実行すると,NSLogが二回出力されるのが確認できます.
実際のdelegateメソッドの中では色々と処理を別スレッドでしますので,ViewControllerでdelegateメソッドがいつ呼ばれるかは判りません.