【问题标题】:Unrecognized selector sent to instance was thrown while invoking xxx on target在目标上调用 xxx 时抛出无法识别的发送到实例的选择器
【发布时间】:2021-08-17 07:52:31
【问题描述】:

我在 AppDelegate.m 中声明了一个新方法,比如:

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

在我的 AppDelegate.h 中:

- (void)aMethod;

在我的 anotherClass.m 中:

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

当我在 anotherClass.m 中运行代码时,我得到了错误。有谁知道我错在哪里?

【问题讨论】:

  • 你声明的函数接受一个字典并返回一个指向UIApplication的指针。您正在调用的函数没有传递任何参数。该错误表示未找到名为 aMethod 的不接受任何参数的方法
  • 复制粘贴完整的错误信息。选择器应该有帮助。但如前所述,[appDelegate aMethod] 可以,如果您声明:-(void)aMethod{...}。哦,在Objective-C中,不要在之前什么都没有的方法中使用:,这是一种冗长的语言,所以实际上-(void):(UIApplication *)aMethod :(NSDictionary *)launchOptions完全不清楚......它可能是-(void)aMethodWithApplication: (UIApplication *)application andLaunchOptions:(NSDictionary *)launchOptions然后是[appDelegate aMethodWithApplication: [UIApplication sharedApplication] andLaunchOptions: ???]

标签: ios objective-c react-native-ios appdelegate


【解决方案1】:

发生错误是因为 .h 和 .m 中的方法的签名不匹配,而对于外部类,.h 文件是相关的。

但是还有一个更严重的错误/误解。实际上,您正在扩展 UIApplicationDelegate,这没有任何意义。将特定实例作为第一个参数传递的方法仅在在声明 delegate 的实例中调用时才有用,在您的情况下为 UIApplication

AppDelegate 中声明但从任意类调用的方法的签名应该与普通方法相同

.h

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

.m

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

并使用它

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-08-28
    • 2012-07-24
    相关资源
    最近更新 更多