我正在尝试在master和detail中实现一个带有NavigationController的SplitViewController。我一直在学习本教程,但我仍然遇到了一个相当奇怪的问题。当我尝试调用委托方法时,我得到-[UINavigationController selectedStudent:]: unrecognized selector sent to instance...
任何帮助都将不胜感激。
这是代码:
学生选拔代表.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表示拆分视图的主视图。在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;
}
附言:几个小时以来,我一直在寻找解决方案。
[splitViewController.viewControllers objectAtIndex:1]
是UINavigationController
,而不是StudentDetail
。
错误消息告诉您UINavigationController
没有selectedStudent
属性。
您的代理指向的不是StudentDetail
,而是一个导航控制器,它甚至没有实现< StudentSelectionDelegate>
。然而,由于您指定了类型转换,Objective C不能警告您所转换的对象实际上并不是您所转换为的类
你应该考虑像苹果的代码那样对对象进行类型检查,以确保对象是你期望的类
这是更正后的代码:
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
,但本可以避免出现异常。