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

3

我正在使用storyboard开发一个iPad应用程序。在我的应用程序中,我使用segue modal presentation从第一个视图控制器连接了一个模态视图控制器。该模态视图通过在模态视图中出现的一个按钮进行关闭。如何在不使用segue的情况下从模态视图控制器传递一个字典到第一个视图控制器。


使用协议是将信息传递回上一个控制器的最佳方式。 - Charan Giri
5个回答

5
您可以使用通知进行传值。
// 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]

1

0
- (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

}

0

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

在您的视图控制器中,将其写入.h文件中

@class yourclassName;

typedef void (^yourclassName回调) (NSDictionary*);

@protocol yourclassName代理 @required - (void)yourclassNamedidReceiveData:(NSDictionary *)dataDict;

@end

in .m file

@synthesize delegate=_delegate;
@synthesize callbackBlock=_callbackBlock;

在某些需要返回信息的按钮操作中,可以写入以下代码:
[self yourclassNamedidReceiveData:yourDictHere]; // you can use any as per your requirement

注意:yourclassNamedidReceiveData方法在一个类中声明,现在在另一个类中实现,您将从该类中调用此类。
在您之前的控制器中(您尝试在其中呈现一个类(假设classA和classB),第一个类是classA,呈现的类是classB),在ClassA中。
- (void) yourclassNamedidReceiveData:(NSDictionary *)dataDict
{

}

注意* 不要忘记将委托设置为classB,例如:classBObject.delegate=self;
希望这能帮到你


我尝试了你上面提到的方法,但是我得到了3个错误。synthesize delegate=_delegate; synthesize callbackBlock=_callbackBlock; 错误:属性实现必须在接口'MyclassName'中。然后,在调用函数的地方出现一个错误..[self yourclassNamedidReceiveData:yourDictHere]; 错误-没有为'MyclassName'声明可见的接口来声明选择器'MyclassNamedidReceiveData'。请帮助我解决这个错误。 - Nithin U S

0

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

接下来,在按钮的IBAction中(通过Interface Builder设置或通过addTarget:self action:forControlEvents:设置),你可以调用[self performSegueWithIdentifier:@"YourSegueIdentifier" sender:button];

你可以像往常一样,在- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender中将数据传递给第二个控制器。


我不想使用segue。如果我使用segue,我的第一个视图将重新加载,我不想要这个。 - Nithin U S

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接