Calling a method from another class in Objective C

后端 未结 5 1000
鱼传尺愫
鱼传尺愫 2020-12-03 09:28

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 me

5条回答
  •  南笙
    南笙 (楼主)
    2020-12-03 09:43

    you can do this using notificationCenter. e.g

    Class A .h

    @interface A: UIViewController
    -(void)classAandBMethod;
    @end
    

    .m

    @implementation
    -(void)willPushToClassB
    {
     [[NSNotificationCenter defaultCenter] removeObserver:self];
     [[NSNotificationCenter defaulCenter] addObserver:self selector:@selector(classAandBMethod) name:@"classAandBMethod_name" object:nil];
     //push class B
     ClassB *b = [ClassB alloc] initWithNibName:@"ClassB" ........];
     [self.navigationController pushViewController:b animated:YES];
    }
    @end
    

    when you call the method in ClassB:

    //this method in classB will call the method in Class a.
    -(void)callMethodInClassA{
     NSNotification *subject = [NSNotification defaultCenter];
     [subject postNotificationName:@"classAandBMethod_name" object:nil userinfo:whatEverInfoYouWant_dict];
     [subject removeObserver:self];
    }
    

提交回复
热议问题