对iOS 中自定义delegate的理解

    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,系统的这里就不再说了,思想都是如此,大同小异。
 
 
 

                
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值