delegate是iOS开发中的非常重要的知识,也是必须掌握的,因为他用着很方便,跟广播来比,更显示出了他的优越性。
delegate在中文的书中被翻译成了,代理或者委托。顾名思义,就是本来该自己完成的工作,却交给别人来做,也就是找了个代理,委托给了别人。这就是代理的意思,也是代理的思想。其实在object-c来看,其实它的本质就是一个协议而已,你继承了协议,你就要完成协议中定义的方法。这样实现这个这个delegate协议的类或者说是
controller便成了原来那个协议的代理。但是这个协议,一般是在一个类中定义的,也就是在那个想要委托别人干活的类来定义的。
<pre name="code" class="objc"><pre name="code" class="objc"><pre name="code" class="objc">//
// FKGameView.h
// Link
//
// Created by yeeku on 13-7-16.
// Copyright (c) 2013年 crazyit.org. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "FKGameService.h"
#import "FKLinkInfo.h"
#import "FKPiece.h"
@class FKGameView;
<span style="color:#ff0000;">@protocol FKGameViewDelegate <NSObject>
- (void) checkWin: (FKGameView*)gameView;
@end</span>
@interface FKGameView : UIView
// 游戏逻辑的实现类
@property (nonatomic, strong) FKGameService* gameService; //①
// 连接信息对象
@property (nonatomic, strong) FKLinkInfo* linkInfo;
// 保存当前已经被选中的方块
@property (nonatomic, strong) FKPiece* selectedPiece;
@property (nonatomic, strong) id<FKGameViewDelegate> delegate;
// 开始游戏方法
- (void) startGame;
@end
这便定义了一个delegate协议,也就是那个要委托别人的委托者或者叫做被代理者。
<pre name="code" class="objc">//
// FKViewController.h
// Link
//
// Created by yeeku on 13-7-16.
// Copyright (c) 2013年 crazyit.org. All rights reserved.
//
#import <UIKit/UIKit.h>
#import "FKGameView.h"
<span style="color:#ff0000;">@interface FKViewController : UIViewController <UIAlertViewDelegate
, FKGameViewDelegate></span>
@property (strong, nonatomic) IBOutlet UIButton *startBn;
@property (strong, nonatomic) IBOutlet UILabel *timeText;
@end
<pre name="code" class="objc">//
// FKViewController.m
// Link
//
// Created by yeeku on 13-7-16.
// Copyright (c) 2013年 crazyit.org. All rights reserved.
//
#import "FKViewController.h"
#import "FKGameView.h"
#import "Constants.h"
#import "FKPiece.h"
@interface FKViewController ()
@end
@implementation FKViewController
<span style="color:#ff0000;">- (void)checkWin:(FKGameView *)gameView</span>
{
// 判断是否还有剩下的方块, 如果没有, 游戏胜利
if (![gameView.gameService hasPieces])
{
// 游戏胜利
[successAlert show];
// 停止定时器
[timer invalidate];
// 更改游戏状态
isPlaying = NO;
}
}
@end
这里便是那个被委托者或者代理。
<pre name="code" class="objc">当然一定要加上这样一句。gameView.delegate = self;
这样就可以了。
当然上面是自定义的delegate,还有很多系统的delegate,系统的这里就不再说了,思想都是如此,大同小异。