ios - 在 View Controller 之间传递数据

标签 ios objective-c swift model-view-controller uiviewcontroller

我对iOS和Objective-C以及整个MVC模式都不熟悉,我坚持以下几点:
我有一个作为数据输入表单的视图,我想给用户选择多个产品的选项。产品在另一个视图中以UITableViewController列出,我已启用多个选择。
我的问题是,如何将数据从一个视图传输到另一个视图?我将在数组中保留UITableView上的选择,但如何将其传递回上一个数据输入窗体视图,以便在提交窗体时将其与其他数据一起保存到核心数据?
我浏览了一下,看到一些人在app委托中声明了一个数组。我读了一些关于单例的文章,但不明白它们是什么,我读了一些关于创建数据模型的文章。
正确的方式是什么?我该怎么做?

最佳答案

这个问题在stackoverflow上似乎非常流行,所以我想我会尝试给出一个更好的答案,帮助像我这样从iOS开始的人。
我希望这个答案足够清楚,让人们理解,我没有遗漏任何东西。
向前传递数据
将数据从另一个视图控制器转发到视图控制器。如果要将对象/值从一个视图控制器传递到另一个视图控制器(可能要将其推送到导航堆栈),则可以使用此方法。
在这个例子中,我们将有ViewControllerAViewControllerB
要将BOOL值从ViewControllerA传递到ViewControllerB,我们将执行以下操作。
ViewControllerB.h中为BOOL创建属性

@property (nonatomic, assign) BOOL isSomethingEnabled;

ViewControllerA中,您需要告诉它关于ViewControllerB的信息,因此使用
#import "ViewControllerB.h"

然后,如果要加载视图,例如didSelectRowAtIndex或某些IBAction,则需要在ViewControllerB中设置属性,然后再将其推送到nav stack。
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.isSomethingEnabled = YES;
[self pushViewController:viewControllerB animated:YES];

这将把isSomethingEnabled中的ViewControllerB设置为BOOLYES
使用Segues转发数据
如果您使用的是情节串连板,您很可能使用segue,并需要此过程来传递数据。这与上面的类似,但不是在推送视图控制器之前传递数据,而是使用一个名为
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender

因此,要将aBOOLViewControllerA传递到ViewControllerB,我们将执行以下操作:
ViewControllerB.h中为BOOL创建属性
@property (nonatomic, assign) BOOL isSomethingEnabled;

ViewControllerA中,您需要告诉它关于ViewControllerB的信息,因此使用
#import "ViewControllerB.h"

在故事板上创建一个从ViewControllerAViewControllerB的段并给它一个标识符,在这个例子中我们称它为"showDetailSegue"
接下来,我们需要将方法添加到执行任何segue时调用的ViewControllerA中,因此我们需要检测调用了哪个segue,然后执行一些操作。在我们的示例中,我们将检查"showDetailSegue",如果执行了该操作,我们将把BOOL值传递给ViewControllerB
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"showDetailSegue"]){
        ViewControllerB *controller = (ViewControllerB *)segue.destinationViewController;
        controller.isSomethingEnabled = YES;
    }
}

如果您的视图嵌入到导航控制器中,则需要将上面的方法稍微更改为以下方法
-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
    if([segue.identifier isEqualToString:@"showDetailSegue"]){
        UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
        ViewControllerB *controller = (ViewControllerB *)navController.topViewController;
        controller.isSomethingEnabled = YES;
    }
}

这将把isSomethingEnabled中的ViewControllerB设置为BOOLYES
传回数据
要将数据从ViewControllerB传递回ViewControllerA需要使用协议、委托或块,后者可以用作回调的松耦合机制。
为此,我们将使ViewControllerA成为ViewControllerB的代表。这允许ViewControllerB将消息发送回ViewControllerA使我们能够发送数据。
要想成为ViewControllerA的代表,它必须符合我们必须指定的ViewControllerB协议。这告诉ViewControllerB它必须实现哪些方法。
ViewControllerA中,在ViewControllerB.h下方,但在#import上方指定协议。
@class ViewControllerB;

@protocol ViewControllerBDelegate <NSObject>
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item;
@end

接下来在@interface中,您需要设置ViewControllerB.h属性并在delegate中合成
@property (nonatomic, weak) id <ViewControllerBDelegate> delegate;

ViewControllerB.m中,我们在弹出视图控制器时调用ViewControllerB上的消息。
NSString *itemToPassBack = @"Pass this value back to ViewControllerA";
[self.delegate addItemViewController:self didFinishEnteringItem:itemToPassBack];

这是给delegate的。现在在ViewControllerB中,告诉ViewControllerA.h导入ViewControllerA并遵守其协议。
#import "ViewControllerB.h"

@interface ViewControllerA : UIViewController <ViewControllerBDelegate>

ViewControllerB中,从我们的协议中实现以下方法
- (void)addItemViewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)item
{
    NSLog(@"This was returned from ViewControllerB %@",item);
}

在将ViewControllerA.m推送到导航堆栈之前,我们需要告诉viewControllerB它的委托是ViewControllerB的,否则我们将得到一个错误。
ViewControllerB *viewControllerB = [[ViewControllerB alloc] initWithNib:@"ViewControllerB" bundle:nil];
viewControllerB.delegate = self
[[self navigationController] pushViewController:viewControllerB animated:YES];

工具书类
Using Delegation to Communicate With Other View Controllers在视图控制器编程指南中
Delegate Pattern
NSNotification中心
这是传递数据的另一种方式。
// add observer in controller(s) where you want to receive data
[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleDeepLinking:) name:@"handleDeepLinking" object:nil];

-(void) handleDeepLinking:(NSNotification *) notification {
    id someObject = notification.object // some custom object that was passed with notification fire.
}

// post notification
id someObject;
[NSNotificationCenter.defaultCenter postNotificationName:@"handleDeepLinking" object:someObject];

将数据从一个类传回另一个类(类可以是任何控制器、网络/会话管理器、UIView子类或任何其他类)
块是匿名函数。
此示例将数据从控制器B传递到控制器A
定义块
@property void(^selectedVoucherBlock)(NSString *); // in ContollerA.h

添加块处理程序(侦听器)
需要值的地方(例如,您需要在ControllerA中得到API响应,或者您需要在a上获得ContorllerB数据)
// in ContollerA.m

- (void)viewDidLoad {
    [super viewDidLoad];
    __unsafe_unretained typeof(self) weakSelf = self;
    self.selectedVoucherBlock = ^(NSString *voucher) {
        weakSelf->someLabel.text = voucher;
    };
}

转到控制器B
UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"Main" bundle:nil];
ControllerB *vc = [storyboard instantiateViewControllerWithIdentifier:@"ControllerB"];
vc.sourceVC = self;
    [self.navigationController pushViewController:vc animated:NO];

防火块
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath: 
(NSIndexPath *)indexPath {
    NSString *voucher = vouchersArray[indexPath.row];
    if (sourceVC.selectVoucherBlock) {
        sourceVC.selectVoucherBlock(voucher);
    }
    [self.navigationController popToViewController:sourceVC animated:YES];
}

Another Working Example for Blocks

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

相关文章:

ios - 魔法记录: nil is not a legal NSPersistentStoreCoordinator

ios - 如何自定义 Google Maps for iOS Swift 的 "myLocationButton"

ios - 如何根据滑出菜单导航到不同的 View Controller

ios - 将 SKShader 应用于多个图层

ios - 覆盖 setContentOffset

ios - 如何在用户点击 iPhone 屏幕的任何部分时关闭以编程方式创建的 UIView

iphone - 如何在 iPhone 上连接字符和字符串?

iphone - 从客户端发送推送通知

ios - 3rd 方框架 swift 文件中的编译器错误

ios - NSMutableURLRequest 不改变 HTTPMethod