protocol应用两个controller之间或者controller与自定义UIView之间的相互调用。

      它的应用类似java或者C#里的interface。假设A调用B,B回调A,那么就可以如此设计:

      首先:定义一个protocal:

 @protocol PtlChart


@optional
-(void) callBack:(id)arg;

@required
-(void) loadData;
@end

 

 

      第二步:在B里定义protocal的delegate:

代码
//B.h
@interface B : UIView {
     id
<PtlChart>      _delegate;
}

@property (nonatomic,retain)       id
<PtlChart>  delegate;

@end

//B.m:
#import "B.h"


@implementation B

@synthesize 
delegate = _delegate;

- (void)dealloc {
     [_delegate release];

@end

 

 

      第三步:在A里调用B时,把delegate传递过去:

代码
//A.h:
@interface A : UIViewController<PtlChart> 

@end
//A.m:
#import "A.h"

@implementation A

- (void) loadData {
     A 
*= [[A alloc] init];
    [a setDelegate:self];   
//<<--------- here
   [self.view addSubview:a];
   [a release];
}

-(void) callBack:(id)arg{
    
int i = (int)arg;
    NSLog(
@"callback= %d",i);
}
@end

 

 

     

 

 

 

 

相关文章: