ios学习路线—Objective-C(Protocol)

来源:互联网 发布:c语言中使用thumb指令 编辑:程序博客网 时间:2024/04/28 00:06

protocol(协议):我的理解就是定义这么一个东西。以后就按这里的规定来办事。
delegate(委托):就是把事情委托给别人去办。
@required 就是必须去办的。
@optional则是可做或不做。

关于delegate protocol 网上有一个例子讲的非常形象:
我上班的工作主要内容包括 (1)写代码(2)写文档(3)测试程序(4)接电话(5)会见客户
(1)(2)我自己全权负责,但是后面(3)(4)(5)我不想或者不方便自己做,所以我想找个助手(delegate)帮我做这些事,于是我定了一个招聘要求(Protocol),里写明我的助手需要会做(3)(4)(5)这三件事。很快,我招到一个助手。
即:我.delegate = 助手;
于是以后每当我遇到需要测试程序或者接电话的活,我就把他转交给助手(delegate)去处理,助手处理完后如果有处理结果(返回值)助手会告诉我,也许我会拿来用。如果不需要或者没有结果,我就接着做下面的事。

示例
在DelegateTest.h里实现protocol

#import <UIKit/UIKit.h>//协议里的方法@protocol DelegateTestDelegate<NSObject>//如果别的类也用到了这个protocol 那么就可以直接调用了。-(void)print:(NSInteger)number;        -(void)print;@end@interface DelegateTest : NSObject@property(nonatomic,assign)id<DelegateTestDelegate> delegate;@property(nonatomic,assign)NSInteger nb;-(void)printPublic;         //公开@end

DelegateTest.m 文件

#import "DelegateTest.h"@interface DelegateTest ()@end@implementation DelegateTest//如果这个类是基于UIControllView的话。可以直接在ViewDidLoad里面调用。那么效果也是一样的  这里就相当于别的类里调用这个方法。起到激活的作用-(void)printPublic{    [delegate print];    [delegate print:nb];}@end

ViewController.h 文件

#import <UIKit/UIKit.h>#import "DelegateTest.h"@interface ViewController : UIViewController<DelegateTestDelegate>  //这里的DelegateTestDelegate也就相当于UITableView里的UITableViewDelegate{    DelegateTest *delegateTest;}@property (nonatomic, assign)DelegateTest *delegateTest;@end

ViewController.m 文件

#import "ViewController.h"@interface ViewController ()@end@implementation ViewController@synthesize delegateTest;- (void)viewDidLoad{    [super viewDidLoad];    delegateTest = [[DelegateTest alloc]init];    [delegateTest setDelegate:self];  //设置代理    [delegateTest printPublic ];  //选择调用delegateTest 里的这个方法。然后就可以调用下面的print了。也就相当于把print给激活了    // Do any additional setup after loading the view, typically from a nib.}- (void)viewDidUnload{    [super viewDidUnload];    // Release any retained subviews of the main view.}//调用DelegateTest  protocol 里面的方法-(void)print{    NSLog(@"qingjoin print succeed");}-(void)print:(NSInteger)number{    NSLog(@"%d",number);}- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation{    return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);}@end
0 0
原创粉丝点击