简体   繁体   中英

Can't call method from second ViewController

I am having problems getting my application to build. I am trying to call a method from ViewController1 in my current ViewController2.

In my .h file of ViewController1 i have declared the method so it is visible.

-(void)saveLocation;

In my ViewController2.h file i have the following

    #import "ViewController1.h"



@interface ViewController2 : UIViewController

@property (nonatomic,assign) ViewController1 *MethodSave;

@end

and in my ViewController2.m

[self.MethodSave saveLocation];

it doesn't work and I've tried to fix it for a while now. Any help would be great. Thank you

I think you have only declared a property @property (nonatomic,assign) ViewController1 *MethodSave; but have not allocated this property. So first allocate it then call the function.

MethodSave = [ViewController1 new];
[self.MethodSave saveLocation];

also declare the property as strong not assign @property (nonatomic,strong) ViewController1 *MethodSave; this should work.

and try to declare variable with camel case.

Are you also importing ViewController2 in your ViewController1? According to my own Google search your problem could be a circular dependency.

If this is the case, instead of importing ViewController1 in ViewController2, create a protocol in ViewController2.h and replace the ViewController1 property with an id that conforms to that protocol.

Add the following in ViewController2.h:

@protocol ViewController2Delegate<NSObject>
@required
-(void)saveLocation;
@end

@interface ViewController2:UIViewController
@property id<ViewController2Delegate> *delegate;
@end

and add this to ViewController1.h:

@interface ViewController1:UIViewController <ViewController2Delegate>

and then set the delegate to an instance of ViewController1 (if you're loading ViewController2 from ViewController1, it would be self ), and be sure to remove the import from ViewController2.

I'm doing this by memory so it may not work copy and pasted, but hopefully this points you in the right direction.

try this ,

ViewController1 *MethodSave = [[ViewController1 alloc]init];
[MethodSave saveLocation];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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