gpt4 book ai didi

iOS7 在导航 Controller 推送 View 设置中按协议(protocol)向后传递数据

转载 作者:行者123 更新时间:2023-11-28 22:07:00 24 4
gpt4 key购买 nike

我在我的代码中尝试了许多自定义委托(delegate)示例,将数据从 View B 发送回父 View A。为什么我得到 NULL?应该有一些我想念的东西。请帮忙。我如何调用 setupDate 以在父 View 中接收 (NSDate *)setAlarmDate?

父 View

#import "SetupViewController.h"

@interface ViewController : UIViewController <SetupViewControllerDelegate> {
NSTimer *timer;
}
@end

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
if ([[segue identifier] isEqualToString:@"setupview"]) {
NSLog(@"prepare for segue");
SetupViewController *svc = [[SetupViewController alloc] init];
svc.delegate = self;

-(void)setupDate:(NSDate *)setAlarmDate{
NSLog(@"Hey Hey");
NSLog(@"%@", setAlarmDate);
}
@end

View B

@protocol SetupViewControllerDelegate <NSObject>
@required
-(void)setupDate:(NSDate *)setAlarmDate;
@end

@interface SetupViewController : UIViewController
@property (nonatomic, strong) id <SetupViewControllerDelegate> delegate;
//IB
@property (weak, nonatomic) IBOutlet UIDatePicker *pDatePicker;
@end

.m

#import "SetupViewController.h"
#import "ViewController.h"
@implementation SetupViewController
-(void)viewWillDisappear:(BOOL)animated{
NSDate *date = [self.pDatePicker date];
[[self delegate] setupDate:date];
}
@end

最佳答案

您应该使用 segue 的 destinationViewController 属性访问 UIViewController 而不是分配您自己的实例,这就是为什么您的 alarmDate = NULL .

例如

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
if ([[segue identifier] isEqualToString:@"setupview"])
{
NSLog(@"prepare for segue");
SetupViewController *svc = [segue destinationViewController];
svc.delegate = self;
}
}

此外,正如@Neru 提到的,您的代理人应该是弱者而不是强者。这样做的原因是如果你没有在 dealloc 方法中显式设置 delegate = nil ,你将导致一个 retain cycle。

关于iOS7 在导航 Controller 推送 View 设置中按协议(protocol)向后传递数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23727715/

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