调用委托方法时无法识别的选择器

Unrecognized selector when calling delegate Method

我正在尝试在主视图和详细视图中实现带有 NavigationController 的 SplitViewController。我一直在关注 this tutorial,但我仍然 运行 遇到了一个相当奇怪的问题。 当我尝试调用委托方法时,我得到 -[UINavigationController selectedStudent:]: unrecognized selector sent to instance...

如有任何帮助,我们将不胜感激。

代码如下:

StudentSelectionDelegate.h

#import <Foundation/Foundation.h>
@class Student;
@protocol StudentSelectionDelegate <NSObject>
@required
-(void)selectedStudent:(Student *)newStudent;
@end

StudentDetail 表示拆分视图中的详细信息。 在 StudentDetail.h 我有

#import "StudentSelectionDelegate.h"
@interface StudentDetail : UITableViewController <StudentSelectionDelegate>
...

StudentDetail.m

@synthesize SentStudent;
...
-(void)selectedStudent:(Student *)newStudent
{
    [self setStudent:newStudent];
}

StudentList 代表 splitview 的主人。在 StudentList.h 我有 :

#import "StudentSelectionDelegate.h"
...
@property (nonatomic,strong) id<StudentSelectionDelegate> delegate;

在StudentList.m在didSelectRowAtIndexPath

[self.delegate selectedStudent:SelectedStudent];

没有"SelectedStudent"不为空

最后 AppDelegate.m

#import "AppDelegate.h"
#import "StudentDetail.h"
#import "StudentListNew.h"
...
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleLightContent];

    UISplitViewController *splitViewController = (UISplitViewController *)self.window.rootViewController;
    UINavigationController *leftNavController = [splitViewController.viewControllers objectAtIndex:0];
    StudentListNew  *leftViewController = (StudentListNew *)[leftNavController topViewController];
    StudentDetail  *rightViewController = [splitViewController.viewControllers objectAtIndex:1];

    leftViewController.delegate = rightViewController;

    return YES;
}

P.S。我一直在寻找解决方案几个小时。

[splitViewController.viewControllers objectAtIndex:1]UINavigationController,不是 StudentDetail

错误消息告诉您 UINavigationController 没有 selectedStudent 属性。

您的委托没有指向 StudentDetail,而是指向导航控制器,它甚至没有实现 < StudentSelectionDelegate>。但是,由于您指定了类型转换,Objective C 无法警告您您转换的对象实际上不是您转换它的那种 class。

您应该考虑对对象进行类型检查,就像 Apple 的代码所做的那样,以确保对象是您期望的 class。

这是更正后的代码:

UINavigationController *rightNavController = [splitViewController.viewControllers objectAtIndex:1];
StudentDetail  *rightViewController = (StudentDetail *)[rightNavController topViewController];
leftViewController.delegate = rightViewController;

至于确保您的委托实现了该方法,

if ([self.delegate respondsToSelector:@selector(selectedStudent:)]) {
    [self.delegate selectedStudent:SelectedStudent];
}

会让你免于异常,尽管你必须使用调试器才能意识到 self.delegate 不是 StudentDetail