gpt4 book ai didi

ios - 调用委托(delegate)方法时无法识别选择器

转载 作者:行者123 更新时间:2023-11-29 01:20:31 25 4
gpt4 key购买 nike

我正在尝试在主视图和详细 View 中实现一个带有 NavigationController 的 SplitViewController。我一直在关注this tutorial ,但是我仍然遇到了一个相当奇怪的问题。当我尝试调用委托(delegate)方法时,我得到 -[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 表示 Split View中的详细信息。在 StudentDetail.h 中我有

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

学生详细信息.m

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

StudentList 委托(delegate) 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;
}

附言几个小时以来,我一直在寻找解决方案。

最佳答案

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

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

您的委托(delegate)没有指向 StudentDetail但是一个导航 Controller ,它甚至没有实现 < StudentSelectionDelegate> .但是,由于您指定了类型转换,Objective C 无法警告您您转换的对象实际上不是您要转换成的类。

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

修改后的代码:

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

至于确保您的委托(delegate)实现该方法,

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

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

关于ios - 调用委托(delegate)方法时无法识别选择器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34656293/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com