I just happened to see this post while researching. Here is a sample code:
ClassA.h file:
#import <Foundation/Foundation.h>
#import "ClassB.h"
@interface ClassA : NSObject <ClassBDelegate>
@end
ClassA.m file:
#import "ClassA.h"
@implementation ClassA
-(void)createAnInstanceOfClassB
{
ClassB *myClassB = [[ClassB alloc]init]; //create an instance of ClassB
myClassB.delegate = self; //set self as the delegate
// [myClassB optionalClassBMethod]; //this is optional to your question. If you also want ClassA to call method from ClassB
}
-(void)calculate
{
NSLog(@"Do calculate thing!"); // calculate can be called from ClassB or ClassA
}
@end
ClassB.h file:
#import <Foundation/Foundation.h>
@protocol ClassBDelegate <NSObject>
-(void)calculate; //method from ClassA
@end
@interface ClassB : NSObject
@property (assign) id <ClassBDelegate> delegate;
//-(void)optionalClassBMethod; //this is optional to your question. If you also want ClassA to call method from ClassB
@end
ClassB.m file:
#import "ClassB.h"
@implementation ClassB
@synthesize delegate;
-(void)whateverMethod
{
[self.delegate calculate]; // calling method "calculate" on ClassA
}
//-(void)optionalClassBMethod //this is optional to your question. If you also want ClassA to call method from ClassB
//{
// NSLog(@"optionalClassBMethod");
// [self whateverMethod];
//}
@end
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…