Home > Software design >  Unrecognized selector sent to instance was thrown while invoking xxx on target
Unrecognized selector sent to instance was thrown while invoking xxx on target

Time:09-16

I declared a new method in AppDelegate.m, like:

-(void):(UIApplication *)aMethod :(NSDictionary *)launchOptions{
......
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions Entity:entity 
     completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
        }else{
        }
    }];
......
}

in my AppDelegate.h:

- (void)aMethod;

in my anotherClass.m:

  AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
  [appDelegate aMethod];

And when I run the code in anotherClass.m I got the error. Does anyone know where I am wrong?

CodePudding user response:

The error occurs because the signatures of the methods in .h and .m don't match and for external classes the .h file is relevant.

But there is a more significant mistake/misunderstanding. Actually you are extending UIApplicationDelegate which makes no sense. Methods which pass a specific instance as first parameter are only useful when being called in the instance where the delegate is declared in, in your case in UIApplication.

The signature of a method declared in AppDelegate but called from an arbitrary class should be the same as a normal method

.h

-(void)aMethod:(NSDictionary *)launchOptions;

.m

-(void)aMethod:(NSDictionary *)launchOptions { 
    ...
    [UMessage registerForRemoteNotificationsWithLaunchOptions:launchOptions 
                                                       Entity:entity 
                                            completionHandler:^(BOOL granted, NSError * _Nullable error) {
        if (granted) {
        }else{
        }
    }];
...
}

and use it

AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSDictionary  *options = ...
[appDelegate aMethod: options];
  • Related