简体   繁体   English

Objective-C - 来自其他 controller 的访问方法

[英]Objective-C - Access method from other controller

i have a little question about getting access to a method in another controller, nu i am trying this.我对访问另一个 controller 中的方法有一个小问题,我正在尝试这个。 So for example i have the controller A and B. In the controller A i have programmed a method, now i want to get access this through controller B.例如,我有 controller A 和 B。在 controller A 中,我编写了一个方法,现在我想通过 controller B 访问它。

What i have done in class A in the header file:我在 header 文件中的 class A 中做了什么:

+(void)goBack;

and in the implementation file:并在实现文件中:

+(void)goBack {
NSLog(@"go back");
}

in the controller B i do this to get access to the method in controller A:在 controller B 中,我这样做是为了访问 controller A 中的方法:

+(void)goPreviousArticle:(id)sender {
ViewProductInformation_ViewController *theInstance = [[ViewProductInformation_ViewController alloc] init];
[theInstance goBack];
}

However when i execute the program, then it does not work, the program just shuts down, when i do command click on the function goBack in controller B i get referred to the method in controller A.但是,当我执行程序时,它不起作用,程序只是关闭,当我执行命令单击 controller B 中的 function goBack 时,我参考了 Z594C103F2C6E010C3D8AB059 中的方法。

Does anybody have an idea what the problem could be?有人知道问题可能是什么吗?

thanks in advance,提前致谢,

snowy下雪的

It's quite easy... you just mixed the class and instance-method declaration: The "+" sign indicates that the method is a class method.这很容易......您只需混合 class 和实例方法声明:“+”号表示该方法是 class 方法。 In your case it should be a "-" so在你的情况下,它应该是一个“-”所以

-(void)goBack; // a instance method declaration!

Hope this helps.希望这可以帮助。

Class vs instance method declaration... see also What is the difference between class and instance methods? Class 与实例方法声明...另请参阅class 和实例方法有什么区别?

You are declaring goBack as a CLASS method (with the preceding "+").您将 goBack 声明为 CLASS 方法(带有前面的“+”)。 Change the + to a -.将 + 更改为 -。

Since goBack is a static method of Class A, you don't need an instance of A to call it's method, you can just call it like so:由于 goBack 是 Class A 的 static 方法,因此您不需要 A 的实例来调用它的方法,您可以像这样调用它:

[ClassA goBack]; [A 级回退];

You don'y need to declare static functions you can writ like this:你不需要声明 static 函数,你可以这样写:

-(void)goBack {
NSLog(@"go back");
}

In the class A and same in the class B:在 class A 和 class B 中相同:

-(void)goPreviousArticle:(id)sender {
ViewProductInformation_ViewController *theInstance = [[ViewProductInformation_ViewController alloc] init];
[theInstance goBack];
}

Then use them.然后使用它们。 I think in that case application will not crashed.我认为在那种情况下应用程序不会崩溃。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM