0

我正在尝试在 master 和 detail 中实现一个带有 NavigationController 的 SplitViewController。我一直在关注本教程,但是我仍然遇到了一个相当奇怪的问题。当我尝试调用委托方法时,我得到-[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 代表拆分视图的主人。在 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;
}

PS我一直在寻找解决方案几个小时。

4

1 回答 1

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.

于 2016-01-07T13:51:39.657 回答