Call a function from another Class - Obj C

匿名 (未验证) 提交于 2019-12-03 00:56:02

问题:

I'm trying to figure out how I can call a function from another one of my classes. I'm using a RootViewController to setup one of my views as lets say AnotherViewController

So in my AnotherViewController im going to add in on the .h file

@class RootViewController 

And in the .m file im going to import the View

#import "RootViewController.h" 

I have a function called:

-(void)toggleView { //do something } 

And then in my AnotherViewController I have a button assigned out as:

    -(void)buttonAction { //} 

In the buttonAction I would like to be able to call the function toggleView in my RootViewController.

Can someone clarify on how I do this.

I've tried adding this is my buttonAction:

RootViewController * returnRootObject = [[RootViewController alloc] init];     [returnRootObject toggleView]; 

But I dont think that's right.

回答1:

You'll want to create a delegate variable in your AnotherViewController, and when you initialize it from RootViewController, set the instance of RootViewController as AnotherViewController's delegate.

To do this, add an instance variable to AnotherViewController: "id delegate;". Then, add two methods to AnotherViewController:

- (id)delegate {      return delegate; }  - (void)setDelegate:(id)newDelegate {      delegate = newDelegate; } 

Finally, in RootViewController, wherever AnotherViewController is initialized, do

[anotherViewControllerInstance setDelegate:self]; 

Then, when you want to execute toggleView, do

[delegate toggleView]; 

Alternatively, you could make your RootViewController a singleton, but the delegate method is certainly better practice. I also want to note that the method I just told you about was Objective-C 1.0-based. Objective-C 2.0 has some new property things, however when I was learning Obj-C this confused me a lot. I would get 1.0 down pat before looking at properties (this way you'll understand what they do first, they basically just automatically make getters and setters).



回答2:

I tried out the NSNotificationCentre - Works like a charm - Thanks for your reply. I couldn't get it running but the NS has got it bang on.

[[NSNotificationCenter defaultCenter] postNotificationName:@"switchView" object: nil]; 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!