gpt4 book ai didi

ios - 将数据传递给根 Controller

转载 作者:行者123 更新时间:2023-11-28 19:14:48 26 4
gpt4 key购买 nike

我正在开发一个联系人应用程序。我想通过打开这样的新 View 来添加联系人:

RootViewController.m... 它有一个名为 contacts 的 NSMutableArray

- (IBAction)addContact:(id)sender {

AddContViewController *cont = [[AddContViewController alloc]init];
[self.navigationController presentViewController:cont animated:YES completion:nil];

}

然后回来将联系人添加到 Root View Controller 的数组中:

AddContViewController.m

- (IBAction)acceptAction:(id)sender {


if ([[firstName text] length] < 1 && [[lastName text] length] < 1)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Oh no!" message:@"Invalid contact information!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
}
else{

//创建联系人并将其放入 Root View Controller 的数组中

   Contact *cont = [[Contact alloc]initWithFirstName:[firstName text] lastName:[lastName text] andDOB:[dobPicker date]];

//现在我不知道该怎么办....

    [self dismissViewControllerAnimated:YES completion:^{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Success!" message:@"Contact added successfully!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
}];
}
}

最佳答案

您应该使用委托(delegate)将新的 Contact 对象传达给您的 RootViewController。

定义协议(protocol)

@protocol AddContDelegate
-(void)didAddnewContact:(Contact *)contact;
@end

在您的 AddContViewController 上有一个委托(delegate)属性:

@property (nonatomic, assign) id<AddContDelegate> delegate;

在您的 addContact: 方法中分配委托(delegate):

- (IBAction)addContact:(id)sender {

AddContViewController *cont = [[AddContViewController alloc]init];
cont.delegate = self;
[self.navigationController presentViewController:cont animated:YES completion:nil];

}

在 RootViewController 中实现委托(delegate)方法:

-(void)didAddnewContact:(Contact *)contact {
[contacts addObject:contact];
}

从 AddContViewController 调用委托(delegate):

- (IBAction)acceptAction:(id)sender {


if ([[firstName text] length] < 1 && [[lastName text] length] < 1)
{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Oh no!" message:@"Invalid contact information!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
}
else{

Contact *cont = [[Contact alloc]initWithFirstName:[firstName text] lastName:[lastName text] andDOB:[dobPicker date]];

if([self.delegate respondsToSelector:@selector(didAddnewContact:)]) {
[self.delegate didAddnewContact:cont];
}

[self dismissViewControllerAnimated:YES completion:^{
UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"Success!" message:@"Contact added successfully!" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles: nil];
[alert show];
}];
}
}

关于ios - 将数据传递给根 Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12913565/

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