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

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

- (IBAction)addContact:(id)sender {

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

}


然后返回并将联系人添加到根视图控制器的数组中:

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{


//创建联系人并将其放入根视图控制器的数组中

   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];
        }];
    }
}

最佳答案

有几种方法可以将数据传回。我建议设置一个委托方法。
在任何导入之后,将其添加到AddContViewController.h的顶部:

@class addContViewController
@protocol addContViewControllerDelegate <NSObject>
-(void)addContViewController:(addContViewController *)controller didAddContact:(Contact *)contact;
@end


并在接口部分后添加

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


然后在RootViewController.h中将协议添加到接口行<addContViewControllerDelegate>
现在,在推送新视图之前,在RootViewController.m方法addContact中添加:

cont.delegate = self;


现在,在您的AddContViewController.m中,而不是关闭视图,请调用:

[self.delegate addContViewController:self didAddContact:cont];


这将在RootViewController中调用一个新方法,该方法将通过Contact,在这里您可以根据需要使用它,但是首先关闭视图:

-(void)addContViewController:(addContViewController *)controller didAddContact:(Contact *)contact {
self dismissViewControllerAnimated:YES;

}

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

10-09 18:44