我有两个视图控制器,HomeViewController
和AddViewController
。 HomeViewController
是AddViewController
的代表。
问题在于,当我点击"取消" AddViewController
中的按钮,回调给委托似乎没有执行。对称地,“取消”按钮的行为就像它甚至没有接线一样。以编程方式,断点似乎表明控件离开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;
}
}
答案 0 :(得分:3)
您丢失了分配AddViewController实例的委托对象,我可以看到它仍然是nil
myAddViewController.delegate = self; // 'self' is an example, should be myHomeViewController instance
编辑:
你在你的代码中调用它:
[self.delegate addViewControllerDidCancel:self.thisActivity];
问问自己delegate
的价值是什么?您已声明它,是的,但您尚未设置其值,因此它必须为nil
。因此,当您实例化AddViewController
时,必须使用我之前编写的行设置委托。