How to call method from one class in another (iOS)

后端 未结 3 1108
闹比i
闹比i 2020-12-01 05:51

This a very basic question but I\'ve searched all over and been unable to find an answer that explains well enough for me to get my head around it.

What I want to do

3条回答
  •  情深已故
    2020-12-01 06:22

    You have two basic options. You can either create or pass-in an instance of the first class to the second class, or you can add a static method to the first class and call it directly using the class object.

    For instance, say you have:

    @interface ClassA : NSObject {
    }
    
    //instance methods
    - (int) addNumber:(int)num1 withNumber:(int)num2;
    
    //static/class methods
    + (int) add:(int)num1 with:(int)num2;
    @end
    
    @implementation ClassA
    - (int) addNumber:(int)num1 withNumber:(int)num2 {
        return num1 + num2;
    }
    
    + (int) add:(int)num1 with:(int)num2 {
        return num1 + num2;
    }
    @end
    

    Then you can do:

    #import "ClassA.h"
    
    @interface ClassB : NSObject {
        ClassA* adder;
    }
    
    //constructors
    - (id) init;  //creates a new instance of ClassA to use
    - (id) initWithAdder:(ClassA*)theAdder;  //uses the provided instance of ClassA
    
    //instance methods
    - (int) add2To:(int)num;
    
    //static/class methods
    + (int) add3To:(int)num;
    @end
    
    @implementation ClassB
    - (id) init {
        if (self = [super init]) {
            adder = [[ClassA alloc] init];
        }
        return self;
    }
    
    - (id) initWithAdder:(ClassA*)theAdder {
        if (self = [super init]) {
            adder = theAdder;
        }
        return self;
    }
    
    - (int) add2To:(int)num {
        return [adder addNumber:2 withNumber:num];
    }
    
    + (int) add3To:(int)num {
        return [ClassA add:3 with:num];
    }
    @end
    

    Note that in most cases, you would use instance methods rather than static methods.

提交回复
热议问题