gpt4 book ai didi

iOS 委托(delegate)取消调用失败

转载 作者:行者123 更新时间:2023-11-28 20:06:01 24 4
gpt4 key购买 nike

我有两个 View Controller ,HomeViewControllerAddViewControllerHomeViewControllerAddViewController 的委托(delegate)。

问题是,当我在 AddViewController 中点击“取消”按钮时,对委托(delegate)的回调似乎没有执行。从症状上看,“取消”按钮的行为就好像它甚至没有连线一样。在编程上,断点似乎表明控制离开了 cancelButton 方法,但从未到达 addViewControllerDidCancel

我相信一切都正确连接,这里是相关代码:

来自 AddViewController.h:

#import <UIKit/UIKit.h>
#import "WMDGCategory.h"
#import "WMDGActivity.h"
@class HomeViewController;


@protocol AddViewControllerDelegate <NSObject>

-(void) addViewControllerDidSave;

-(void) addViewControllerDidCancel:(WMDGActivity *) activityToDelete;

@end

@interface AddViewController : UIViewController <UIPickerViewDataSource,UIPickerViewDelegate>


@property (nonatomic, weak) id <AddViewControllerDelegate> delegate;

来自 HomeViewController.h:

@interface HomeViewController : UITableViewController <UITableViewDataSource,UITableViewDelegate,AddViewControllerDelegate>

来自 HomeViewController.m:

-(void) addViewControllerDidSave
{
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
[localContext MR_saveToPersistentStoreAndWait];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
[self refreshData];

}

-(void) addViewControllerDidCancel:(WMDGActivity *) activityToDelete
{
[activityToDelete MR_deleteEntity];
[self.navigationController dismissViewControllerAnimated:YES completion:nil];
[self refreshData];

}

来自 AddViewController.m:

- (IBAction)cancelButton:(UIBarButtonItem *)sender
{
[self.delegate addViewControllerDidCancel:self.thisActivity];
}

有人能发现我的错误吗?

谢谢!

编辑以回应下面的答案 1:

实际上,我在 HomeViewController 的 prepareFroSegue 方法中这样做了:

- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
NSManagedObjectContext *localContext = [NSManagedObjectContext MR_contextForCurrentThread];
if ([[segue identifier] isEqualToString:@"addModal"])
{
UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
AddViewController *avc = (AddViewController *)navController.topViewController;
avc.delegate = self;
WMDGActivity *addedActivity = (WMDGActivity *)[WMDGActivity MR_createInContext:localContext];
avc.thisActivity = addedActivity;
}

}

最佳答案

您缺少分配 AddViewController 实例的委托(delegate)对象,据我所知,它仍然是 nil

myAddViewController.delegate = self;  // 'self' is an example, should be myHomeViewController instance

编辑:
您在代码中调用它:

[self.delegate addViewControllerDidCancel:self.thisActivity];

问问自己 delegate 的值(value)是什么?你已经声明了它,是的,但是你还没有设置它的值,所以它必须是nil。因此,当您实例化您的 AddViewController 时,您必须使用我之前编写的行设置委托(delegate)。

关于iOS 委托(delegate)取消调用失败,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22107626/

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