您的位置:首页 > 移动开发 > IOS开发

iOS 代理-协议的代码笔记

2014-02-26 15:18 429 查看
1,谁要让别人给自己做事(协议方法里面获得值) 则他必须要加上这么一个代理  

@interface ViewController :UIViewController<TestDelegate,DoSomeDelegate,DoSomeDataSource>
 实现代理方法 等待代理传过来的数值

-(void)changeValue:(NSString *)value;

2,给别人做事  他必须有一个代理的对象 

@property(strong,nonatomic)id<DoSomeDelegate>delegate;

3.给别人做什么事情呢?如下:

 [self.delegatechangeValue:self.text.text];//要做的事情就是:赋值
4 源代码:
    代理类:
.h

//
//  DoSomeObj.h
//  delegate
//
//  Created by linpeng on 14-2-25.
//  Copyright (c) 2014年 linpeng. All rights reserved.
//

#import <Foundation/Foundation.h>
//添加协议
@protocol  DoSomeDelegate, DoSomeDataSource;
@interface DoSomeObj : NSObject

@property(strong,nonatomic)NSString *str1,*str2;
@property(strong,nonatomic)id<DoSomeDelegate>delegate;
@property(strong,nonatomic)id<DoSomeDataSource>datasource;
-(void)Action;
@end

//定义一个协议 :DoSomeDelegate
@protocol DoSomeDelegate <NSObject>

@required
-(void)doSomeDelegateAction:(NSString *)str;

@end

//定义一个协议 :DoSomeDataSource
@protocol DoSomeDataSource <NSObject>

@required
-(void)doSomeDataSourceAction:(NSString *)str;

@end
.m

//
//  DoSomeObj.m
//  delegate
//
//  Created by linpeng on 14-2-25.
//  Copyright (c) 2014年 linpeng. All rights reserved.
//

#import "DoSomeObj.h"

@implementation DoSomeObj
-(id)init
{
if(self=[super init])
{
self.str1 = @"delegate";
self.str2 = @"datasource";
//放着里是没用的   因为这个时候的代理===是空的!!!!
//        [self.delegate doSomeDelegateAction:@"delegate"];
//        [self.datasource  doSomeDataSourceAction:@"datasource"];
}
return  self;
}
//促发代理做一些处理
-(void)Action
{
//前面 DoSomeObj *doSome = [[DoSomeObj alloc] init];doSome.delegate = self;  所以他的代理不是空的
[self.delegate doSomeDelegateAction:self.str1];
[self.datasource  doSomeDataSourceAction:self.str2];
}
@end

使用代理

.h

#import <UIKit/UIKit.h>
#import "TestDelegate.h"
#import "DoSomeObj.h"
@interface ViewController : UIViewController<TestDelegate,DoSomeDelegate,DoSomeDataSource>

@end


.m

//第二个代理
DoSomeObj *doSome = [[DoSomeObj alloc] init];
doSome.delegate = self;
doSome.datasource = self;
//触发代理类赋值
[doSome Action];
#pragma 协议方法
-(void)doSomeDataSourceAction:(NSString *)str
{
lab.text = [NSString stringWithFormat:@"%@--%@",lab.text,str];
}
#pragma 协议方法
-(void)doSomeDelegateAction:(NSString *)str
{
lab.text = [NSString stringWithFormat:@"%@--%@",lab.text,str];

}


download:demo
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: