ios协议和委托

在iPhone开发协议和委托是常接触到的东西,到底什么是协议什么是委托,他们什么关系?

一 协议

(1)协议相当于没有与类相关联的接口,他申明一组方法,列出他的参数和返回值,共享给其他类使用,然后不进行实现,让用它的类来实现这些方法

(2)在任何一个类中,只有声明了协议,都可以实现协议里的方法。

(3)协议不是一个类,更没有父类了。

(3)协议里面的方法经常都是一些委托方法,

二 委托

委托,故名思议就是托别人办事。打个比方:

张三迫切需要一分工作,但是不知道去哪找。于是他就拜托(委托)李四给帮找一份合适工作,但是托人办事得给被人好处啊,于是张三给李四塞了一个红包(协议),于是李四通过自己关系在某公司找了一份文秘的工作(实现协议里面委托方法),于然后他把文秘这份工作给了张三,张三就找到工作了;

三 我们来看一个比较常用的表格单元实现委托和协议

UITableViewDataSource协议和他的委托方法

[cpp] view plaincopy

  1. @protocol UITableViewDataSource<NSObject>
  2. @required
  3. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
  4. // Row display. Implementers should *always* try to reuse cells by setting each cell‘s reuseIdentifier and querying for available reusable cells with dequeueReusableCellWithIdentifier:
  5. // Cell gets various attributes set automatically based on table (separators) and data source (accessory views, editing controls)
  6. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
  7. @optional
  8. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView;              // Default is 1 if not implemented
  9. - (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section;    // fixed font style. use custom view (UILabel) if you want something different
  10. - (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section;
  11. // Editing
  12. // Individual rows can opt out of having the -editing property set for them. If not implemented, all rows are assumed to be editable.
  13. - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath;
  14. // Moving/reordering
  15. // Allows the reorder accessory view to optionally be shown for a particular row. By default, the reorder control will be shown only if the datasource implements -tableView:moveRowAtIndexPath:toIndexPath:
  16. - (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath;
  17. // Index
  18. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView;                                                    // return list of section titles to display in section index view (e.g. "ABCD...Z#")
  19. - (NSInteger)tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index;  // tell table which section corresponds to section title/index (e.g. "B",1))
  20. // Data manipulation - insert and delete support
  21. // After a row has the minus or plus button invoked (based on the UITableViewCellEditingStyle for the cell), the dataSource must commit the change
  22. - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath;
  23. // Data manipulation - reorder / moving support
  24. - (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath toIndexPath:(NSIndexPath *)destinationIndexPath;
  25. @end

这是一个完整协议定义

@protocol  协议名

声明方法

@end

但是我们还看到两个特殊关键字 @required  和 @optional

@required 表示我们用到这个协议的时候必须实现这个协议的方法

@optional 表示我们可选择性实现这些方法,看那个需要我们就去实现,不需要的就不实现

UITableViewDelegate协议和委托方法

[cpp] view plaincopy

  1. @protocol UITableViewDelegate<NSObject, UIScrollViewDelegate>
  2. @optional
  3. // Display customization
  4. - (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath;
  5. // Variable height support
  6. - (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath;
  7. - (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section;
  8. - (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section;
  9. // Section header & footer information. Views are preferred over title should you decide to provide both
  10. - (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section;   // custom view for header. will be adjusted to default or specified header height
  11. - (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section;   // custom view for footer. will be adjusted to default or specified footer height
  12. // Accessories (disclosures).
  13. - (UITableViewCellAccessoryType)tableView:(UITableView *)tableView accessoryTypeForRowWithIndexPath:(NSIndexPath *)indexPath __OSX_AVAILABLE_BUT_DEPRECATED(__MAC_NA,__MAC_NA,__IPHONE_2_0,__IPHONE_3_0);
  14. - (void)tableView:(UITableView *)tableView accessoryButtonTappedForRowWithIndexPath:(NSIndexPath *)indexPath;
  15. // Selection
  16. // Called before the user changes the selection. Return a new indexPath, or nil, to change the proposed selection.
  17. - (NSIndexPath *)tableView:(UITableView *)tableView willSelectRowAtIndexPath:(NSIndexPath *)indexPath;
  18. - (NSIndexPath *)tableView:(UITableView *)tableView willDeselectRowAtIndexPath:(NSIndexPath *)indexPath __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
  19. // Called after the user changes the selection.
  20. - (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath;
  21. - (void)tableView:(UITableView *)tableView didDeselectRowAtIndexPath:(NSIndexPath *)indexPath __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
  22. // Editing
  23. // Allows customization of the editingStyle for a particular cell located at ‘indexPath‘. If not implemented, all editable cells will have UITableViewCellEditingStyleDelete set for them when the table has editing property set to YES.
  24. - (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath;
  25. - (NSString *)tableView:(UITableView *)tableView titleForDeleteConfirmationButtonForRowAtIndexPath:(NSIndexPath *)indexPath __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_3_0);
  26. // Controls whether the background is indented while editing.  If not implemented, the default is YES.  This is unrelated to the indentation level below.  This method only applies to grouped style table views.
  27. - (BOOL)tableView:(UITableView *)tableView shouldIndentWhileEditingRowAtIndexPath:(NSIndexPath *)indexPath;
  28. // The willBegin/didEnd methods are called whenever the ‘editing‘ property is automatically changed by the table (allowing insert/delete/move). This is done by a swipe activating a single row
  29. - (void)tableView:(UITableView*)tableView willBeginEditingRowAtIndexPath:(NSIndexPath *)indexPath;
  30. - (void)tableView:(UITableView*)tableView didEndEditingRowAtIndexPath:(NSIndexPath *)indexPath;
  31. // Moving/reordering
  32. // Allows customization of the target row for a particular row as it is being moved/reordered
  33. - (NSIndexPath *)tableView:(UITableView *)tableView targetIndexPathForMoveFromRowAtIndexPath:(NSIndexPath *)sourceIndexPath toProposedIndexPath:(NSIndexPath *)proposedDestinationIndexPath;
  34. // Indentation
  35. - (NSInteger)tableView:(UITableView *)tableView indentationLevelForRowAtIndexPath:(NSIndexPath *)indexPath; // return ‘depth‘ of row for hierarchies
  36. // Copy/Paste.  All three methods must be implemented by the delegate.
  37. - (BOOL)tableView:(UITableView *)tableView shouldShowMenuForRowAtIndexPath:(NSIndexPath *)indexPath __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_5_0);
  38. - (BOOL)tableView:(UITableView *)tableView canPerformAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_5_0);
  39. - (void)tableView:(UITableView *)tableView performAction:(SEL)action forRowAtIndexPath:(NSIndexPath *)indexPath withSender:(id)sender __OSX_AVAILABLE_STARTING(__MAC_NA,__IPHONE_5_0);
  40. @end

在用的时候,我们现在声明协议

[cpp] view plaincopy

  1. #import <UIKit/UIKit.h>
  2. @interface BIDViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
  3. @property (strong, nonatomic) NSDictionary *names;
  4. @property (strong, nonatomic) NSArray *keys;
  5. @end

实现UITableViewDataSource  UITableViewDelegate协议里面的委托方法

[cpp] view plaincopy

  1. #pragma mark -
  2. #pragma mark Table View Data Source Methods
  3. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
  4. return [keys count];
  5. }
  6. - (NSInteger)tableView:(UITableView *)tableView
  7. numberOfRowsInSection:(NSInteger)section {
  8. NSString *key = [keys objectAtIndex:section];
  9. NSArray *nameSection = [names objectForKey:key];
  10. return [nameSection count];
  11. }
  12. - (UITableViewCell *)tableView:(UITableView *)tableView
  13. cellForRowAtIndexPath:(NSIndexPath *)indexPath {
  14. NSUInteger section = [indexPath section];
  15. NSUInteger row = [indexPath row];
  16. NSString *key = [keys objectAtIndex:section];
  17. NSArray *nameSection = [names objectForKey:key];
  18. static NSString *SectionsTableIdentifier = @"SectionsTableIdentifier";
  19. UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:
  20. SectionsTableIdentifier];
  21. if (cell == nil) {
  22. cell = [[UITableViewCell alloc]
  23. initWithStyle:UITableViewCellStyleDefault
  24. reuseIdentifier:SectionsTableIdentifier];
  25. }
  26. cell.textLabel.text = [nameSection objectAtIndex:row];
  27. return cell;
  28. }
  29. - (NSString *)tableView:(UITableView *)tableView
  30. titleForHeaderInSection:(NSInteger)section {
  31. NSString *key = [keys objectAtIndex:section];
  32. return key;
  33. }
  34. - (NSArray *)sectionIndexTitlesForTableView:(UITableView *)tableView {
  35. return keys;
  36. }

这就就是实现一些里面的委托方法过程运行改程序运行结果

  

该程序源码http://download.csdn.net/detail/duxinfeng2010/4695666

时间: 2024-12-17 19:26:55

ios协议和委托的相关文章

iOS delegate, 代理/委托与协议.

之前知知道iOS协议怎么写, 以为真的跟特么java接口一样, 后来发现完全不是. 首先, 说说应用场景, 就是当你要用一个程序类, 或者说逻辑类, 去控制一个storyboard里面的label, 发现如果直接用 UIStoryboard *mainStoryboard = [UIStoryboard storyboardWithName:@"Main" bundle:[NSBundle mainBundle]];//由storyboard根据myView的storyBoardID来

普通选择器&lt;数据源协议,委托协议&gt;(IOS开发)

-普通选择器必须满足这两个协议,一个为委托协议,一个为数据源协议 -委托协议负责控制控件UI.事件响应, 实现可选 -数据源协议负责控件与应用数据模型的桥梁,一般必须实现 @interface ViewController : UIViewController <UIPickerViewDelegate, UIPickerViewDataSource> // // ViewController.h // PickViewSample // // Created by 李亚坤 on 14-10-

iOS 协议 protocol

iOS中的协议说白了就是方法的声明,只声明不需要实现,实现的部分由遵守协议方完成. 先看个协议的小例子:这个例子是先给出两个协议,再创建两类人遵守协议. 流氓协议(RogueDelegate.h) #import <Foundation/Foundation.h> /**流氓协议*/ @protocol RogueDelegate <NSObject> @required // 必须实现的方法 /**吃*/ - (void) eat; /**骗*/ - (void) lie; @o

swift详解之十一------------协议、委托(代理)模式

协议.委托(代理)模式 注:本小节总结协议以及依靠协议实现委托,这将在以后经常被使用.是一个非常重要的模块 看下官方的定义:协议定义了一个蓝图 , 规定了用来实现某一特定工作或者功能所必须的方法和属性,类.结构体.或者枚举类型都可以遵循协议, 并提供具体实现来完成协议定义的方法和功能 . 任意能够满足协议要求的类型都被成为遵循了这个协议 1.协议的语法 协议的关键字:protocol 协议的语法: protocol Pro1{ //这里定义属性或者方法 } 要使一个类或者结构体遵循某个协议 ,

IOS 协议

一.协议 在ObjC中使用@protocol定义一组方法规范,实现此协议的类必须实现对应的方法.熟悉面向对象的童鞋都知道接口本身是对象行为描述的协议规范.也就是说在ObjC中@protocol和其他语言的接口定义是类似的,只是在ObjC中interface关键字已经用于定义类了. (一)协议注意几点: 1.一个协议可以扩展自另一个协议,例如有的协议是扩展自NSObject,如果需要扩展多个协议中间使用逗号分隔: 2.和其他高级语言中接口不同的是协议中定义的方法不一定是必须实现的,我们可以通过关键

协议与委托

一. 协议 1. 类似于接口,用于定义多个类应该遵守的规范: 并不关心这些类的内部状态数据,也不关心这些类里方法的具体实现,只是规定这些类要提供某些方法. 2. 使用@protocol关键字: 1 @protocol 协议名 <父协议1, 父协议2, ...> 2 { 3 statement... 4 } 注意: 一个协议可以继承多个协议,但是协议不能继承类 方法:只是声明,没有具体实现. 3.  遵守协议的类(即代理): 如果没有实现协议中的所有方法,编译器会发出警告: @optional:

Jquery 在ios上事件委托失效

点击通过js遍历出来的列表,跳转页面.点击事件委托在document上, 像这样: $(document).on("click",".nav",function(){  }) 在web和Android上度没问题,能够正常跳转.但是在ios上点击没有任何反应.原因是:ios上事件委托不能绑定在document和ios上,应该绑定在它的其它父级元素上 $.each(dataall,function(i,item){ str += '<div class="

对iOS中协议和委托的理解

http://www.cnblogs.com/hyzhou/archive/2012/12/10/2810861.html 看到一篇文章,感觉博主写的这个比喻特别形象. 协议相当于一份任务表,有必须完成的任务,也有可选完成的任务.委托相当于实践任务表的个体. 之前想过为什么必须用委托,传值的方式有全局变量,公开类属性等方式,可能委托的优势就在于可以在调用委托的同时处理数据,更新ui. 就能想到这个,算是会用了,但意义还是不明朗,有懂的前辈还望指教一二.

IOS开发之----协议与委托(Protocol and Delegate) 实例解析

1 协议: 协议,类似于Java或C#语言中的接口,它限制了实现类必须拥有哪些方法. 它是对对象行为的定义,也是对功能的规范. 在写示例之前我给大家说下@required和@optional这两个关键字 他们两个是在声明协议的时候用到,@required是必须实现的方法,要不会报黄色警告[email protected]是可选实现!实现还是不实现都不会报警告! 示例: 1 2 3 4 5 6 7 8 9 // GoodChild.h #import @protocol GoodChild -(v