Yaser Sleiman
Yaser Sleiman

Reputation: 95

calling a method inside someClass from AppDelegate Objective-C IOS

I'm trying to call a method that's inside someClass from the AppDelegate class. I usually create an instance and then using that instance, call the method. Like so:

FFAppDelegate *delegate = (FFAppDelegate *) [[UIApplication sharedApplication] delegate];
[delegate someMethod];

I use that ^^ quite a bit in my code and it works perfectly. What I want to do, is switch it around. Instead of calling a method INSIDE the AppDelegate, I want to call a method inside another class FROM the AppDelegate.

SomeClass *test = (SomeClass *) [[UIApplication sharedApplication] delegate];
[test someMethod];

In this case, I keep getting "Terminating app due to uncaught exception 'NSInvalidArgumentException'" error due to "unrecognized selector sent to instance".

Any light shed on the matter would be greatly appreciated! :)

Upvotes: 2

Views: 3383

Answers (3)

Hardik Thakkar
Hardik Thakkar

Reputation: 15951

For Example if you want to Create AlertView only Once and Use it in any UiViewController

So, you can make Method For UIAlertView and Call the Method When you Want

1)In your appDelegate.h file

@property (nonatomic, strong) UIAlertView *activeAlertView;

2) In your AppDelegate.m File

-(void)openAlert
{
    NSString *strMsgPurchase = @"Write your message";
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Buy" message:strMsgPurchase delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Buy",@"Restore", nil];
    [alert setTag:100];
    [alert show];
    self.activeAlertView = alert;
}

3) To Call the Method in which uiview you want

[((AppDelegate *)[[UIApplication sharedApplication] delegate])openAlert];

Note: Define -(void)openAlert Method in Appdelegate.h file

Upvotes: 1

Guo Luchuan
Guo Luchuan

Reputation: 4731

[[UIApplication sharedApplication] delegate]; return your AppDelegate class , not SomeClass

you can use like this :

FFAppDelegate *delegate = (FFAppDelegate *) [[UIApplication sharedApplication] delegate];
[delegate someMethodForSomeClass];

And then in your AppDelegate code someMethodForSomeClass like this :

- (void)someMethodForSomeClass
{
    SomeClass *someClass = _yourSomeClass;
    [someClass someMethod];
}

Upvotes: 2

AdamG
AdamG

Reputation: 3718

Instantiate an instance of the class that you want to send the request from and make the method public (in the .h file). Then import that class into the app delegate and call it.

Like so...

  YourClass * yourClassInstance = [[YourClass alloc] init];
  [yourClassInstance someMethod];

in YourClass.h below the @interface you would declare the method like so

 -(void)someMethod;

So anyone could access it.

Upvotes: 1

Related Questions