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

时间:2014-04-08 08:53:46

标签: ios objective-c storyboard

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

5 个答案:

答案 0 :(得分: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 :(得分:1)

使用委托可能。 仔细阅读

Passing Data between View Controllers

它有简单而完美的答案。

答案 2 :(得分:0)

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

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

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

答案 3 :(得分: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

}

答案 4 :(得分:0)

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

在你所提供的viewcontrooler中,用.h

写这个
@class yourclassName;

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

@protocol yourclassName委托 @需要 - (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方法在一个类中声明,现在它在另一个类中实现,您将在该类中调用此类

在你之前的Controller中(你试图在classA中提出一个类(假设classA和classB),第一个类是classA,而classEC是classB。)在ClassA中

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

}

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

相关问题