协议
协议声明一个编程接口,任何类都可以选择实现这个接口。协议可以声明一组方法,,类可以实现其中一个或多个方法。定义协议的类可以调用协议中的多个方法,这些方法由采用的类实现。
下面通过查看UIAlertView类的实例来说明它。
UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"Hello" message:@"This is an AlertView" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alert show];
事实上UIAlertViewDelegate已经定义好了一些方法,alertView:clickedButtonAtIndex:
//cancelButton为0,依次后排。
willPressAlertView:
didPressAlertView:
alertView:illDismissWithButtonIndex:
alertView:didDismissWithButtonIndex:
alertViewCancel:
如果想实现以上方法就要类遵从如下协议:
@interface AppDelegate :UIViewController <UIAlertViewDelegate>{
//
//
}
如果遵从多个协议就应该像下面这样写:<UIAlertViewDelegate,UITableViewDataSource>
委托
委托只不过是负责处理事件的对象,由另一个对象赋值
UIAlertView*alert=[[UIAlertView alloc] initWithTitle:@"Hello" message:@"This is an AlertView" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil ];
[alert show];
在上面的例子中delegate:self 的意思是,当前对象负责处理UIAlertView类的实例所触发的所有事件,如果不需要处理则只需要设定为delegate:nil