如何在不使用segue的情况下在视图控制器之间传递数据

我正在使用故事板开发iPad应用程序。 在我的应用程序中,我使用segue模态演示从第一个视图控制器连接了一个模态视图控制器。模态视图通过单击模式视图中出现的一个按钮来解除。如何将模态视图控制器中的一个字典传递给第一个视图控制器而不使用Segue公司。

您可以使用通知传递值。

// Send Data NSDictionary *aDictionary = [[NSDictionary alloc] initWithObjectsAndKeys: anObject, @"objectName", anotherObject, @"objectId", nil] autorelease]; [[NSNotificationCenter defaultCenter] postNotificationName:@"AnythingAtAll" object:nil userInfo:aDictionary]; 

您可以从您观察到的入站通知中检索字典。 在发布通知之前添加观察者。

 //this might be in your init method or a viewDidLoad method of your FirstViewController [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(anyAction:) name:@"AnythingAtAll" object:nil]; enter code here 

//获取数据

 -(void)anyAction:(NSNotification *)anote { NSDictionary *dict = [anote userInfo]; AnyClass *objectIWantToTransfer = [dict objectForKey:@"objectName"]; } 

请注意,您应该在dealloc方法中删除作为观察者的对象。

 [[NSNotificationCenter defaultCenter] removeObserver:self] 

使用委托可能。 通过这个

在视图控制器之间传递数据

它有简单而完美的答案。

你可以通过ctrl +从第一个控制器拖动到第二个控制器创建一个没有按钮的Segue(不要忘记给这个segue和标识符)。

Next在按钮的IBAction中(通过Interface Builder设置或通过addTarget:self action:forControlEvents:),您可以调用[self performSegueWithIdentifier:@“YourSegueIdentifier”sender:button];

您可以像往常一样将数据传递给第二个控制器 – (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

 - (void)transitionFromViewController:(UIViewController *)fromViewController toViewController:(UIViewController *)toViewController duration:(NSTimeInterval)duration options:(UIViewAnimationOptions)options animations:(void (^)(void))animations completion:(void (^)(BOOL finished))completion { SecondViewController *secVC = (SecondViewController*)toViewController; secVC.property = self.property } 

使用协议是向先前控制器或任何其他控制器发送信息的最佳过程

在你的viewcontrooler中,你在.h中写了这个

 @class yourclassName; 

typedef void(^ yourclassName Callback)(NSDictionary *);

@protocol yourclassName Delegate @required – (void)yourclassNamedidReceiveData:(NSDictionary *)dataDict;

@结束

 in .m file @synthesize delegate=_delegate; @synthesize callbackBlock=_callbackBlock; 

在某些按钮操作中,您需要将信息传回去那里写下来

 [self yourclassNamedidReceiveData:yourDictHere]; // you can use any as per your requirement 

注意:yourclassNamedidReceiveData方法在一个类中声明,现在它在另一个类中实现,您将在该类中调用此类

在您之前的Controller中(您尝试在ClassA中提供一个类(假设classA和classB),第一个类是classA,并且在ClassA中呈现的类是classB。)

 - (void) yourclassNamedidReceiveData:(NSDictionary *)dataDict { } 

注意*不要忘记将委托设置为classB EX:classBObject.delegate = self;
希望这会有所帮助