Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
361 views
in Technique[技术] by (71.8m points)

iphone - Calling a method from another class in Objective C

I have 2 classes, say class A and class B. Class B is created in class A. I have a method in class A, which needs to be executed in both class A and class B. Calling the method in class A itself is fine. But I am not sure about calling the method in class B. I have tried declaring the method as static, but since I can't use instance variables inside the static method, I think using delegates would be a good idea. Since I am from a C# background, I am not sure about using it in Objective C. Conceptually, I have implemented what I need in C# as shown below. Just wanted to know what the equivalent of it would be in Objective C.

class A
{

    public A()
    {
        B myclass = new B(() => calculate());                
    }

    public void calculate()
    {
        // todo
    }
}

class B
{
    public B(Action calculate)
    {
        calculate();
    }
}

Is it possible to do this using protocols.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...