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

时间:2016-01-07 13:24:58

标签: ios objective-c delegates splitview

我正在尝试使用主控和详细信息中的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;

didSelectRowAtIndexPath

中的StudentList.m中
[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。我一直在寻找解决方案几个小时。

1 个答案:

答案 0 :(得分:1)

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

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

你的代表没有指向StudentDetail,而是指向导航控制器,它甚至没有实现< StudentSelectionDelegate>。但是,由于您指定了强制类型转换,因此Objective C无法警告您所投射的对象实际上并不是您投射它的类。

你应该考虑像Apple的代码一样检查对象的类型,以确保对象是你期望的对象。

以下是更正后的代码:

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,否则

会让你免于异常。