【问题标题】:Best way to pass data from Child Modal VC to the Parent View Controller?将数据从子模态 VC 传递到父视图控制器的最佳方法?
【发布时间】:2013-03-26 17:13:00
【问题描述】:

将数据从子模式视图传递到父视图控制器的最佳方式是什么?

我的 iPad 应用上有一个子模式登录屏幕,我想将用户信息传回给父拆分视图控制器。

我正在考虑使用 NSNotification,但我不确定这是否是将数据传回父级的最简单/最有效的方法。

谢谢! 艾伦

【问题讨论】:

  • 为此我经常使用 NSNotifications。在这种情况下,我不喜欢协议,因为孩子需要了解父母的方法,但这是设计偏好...

标签: ios objective-c xcode modalviewcontroller


【解决方案1】:

你可以通过Protocol得到它,这是最好的方式。

我会告诉你如何创建一个协议的基本思路

另外,请阅读以下问题: How do I create delegates in Objective-C?

以下代码为您提供了协议的基本概念,在下面的代码中,您可以获得从MasterViewControllerDetailViewController 的按钮标题。

#DetailViewController.h

#import <UIKit/UIKit.h>

@protocol MasterDelegate <NSObject>
-(void) getButtonTitile:(NSString *)btnTitle;
@end


@interface DetailViewController : MasterViewController

@property (nonatomic, assign) id<MasterDelegate> customDelegate; 

#DetailViewController.m

if([self.customDelegate respondsToSelector:@selector(getButtonTitile:)])
{
          [self.customDelegate getButtonTitile:button.currentTitle];    
}

#MasterViewController.m

create obj of DetailViewController

DetailViewController *obj = [[DetailViewController alloc] init];
obj.customDelegate = self;
[self.navigationController pushViewController:reportTypeVC animated:YES];

and add delegate method in MasterViewController.m for get button title.

#pragma mark -
#pragma mark - Custom Delegate  Method

-(void) getButtonTitile:(NSString *)btnTitle;
{
    NSLog(@"%@", btnTitle);

}

【讨论】:

  • 太棒了!我会试一试,然后回复你。谢谢。
  • 出于好奇,为什么这种方法比 NSNotification 更好?
【解决方案2】:

我建议as iPatel did 使用delegation 来解决您的问题。父视图控制器和登录视图控制器之间的关系使这种模式很合适。当一个对象创建另一个对象以履行特定职责时,应将委托视为使创建的对象与创建者通信的一种方式。选择委托的一个特别令人信服的理由是,如果要完成的任务可能有多个步骤,需要对象之间的高级交互。您可以查看NSURLConnectionDelegate protocol 作为说明。连接到 URL 是一项复杂的任务,涉及处理响应、满足身份验证挑战、保存下载的数据和处理错误等阶段,连接和委托在连接的整个生命周期内共同处理。

您可能已经注意到,在 Objective-C 中,协议用于实现委托,而无需将创建的对象(在本例中为您的登录视图控制器)与创建它的对象(父视图控制器)紧密耦合。然后,登录视图控制器可以与任何可以接收其协议中定义的消息的对象进行交互,而不是依赖于任何特定的类实现。明天,如果您收到允许任何视图控制器显示登录视图的要求,则登录视图控制器不需要更改。您的其他视图控制器可以实现其委托协议,创建和呈现登录视图,并将自己指定为委托,而登录视图控制器不知道它们的存在。

您在 Stack Overflow 上发现的一些委托示例可能非常令人困惑,并且与内置框架中的委托示例非常不同。必须仔细选择协议的名称和接口,以及分配给每个对象的职责,以便最大限度地重用代码,达到代码的目的。

您应该首先查看内置框架中的许多委托协议,以了解在代码中表达的关系是什么样的。这是另一个基于您的登录用例的小示例。我希望您会发现委托的目的是明确的,所涉及的对象的角色和职责是明确的,并通过它们在代码中的名称来表达。

首先,我们看一下 LoginViewController 的委托协议:

#import <UIKit/UIKit.h>

@protocol LoginViewControllerDelegate;

@interface LoginViewController : UIViewController

// We choose a name here that expresses what object is doing the delegating
@property (nonatomic, weak) id<LoginViewControllerDelegate> delegate;

@end

@protocol LoginViewControllerDelegate <NSObject>

// The methods declared here are all optional
@optional

// We name the methods here in a way that explains what the purpose of each message is
// Each takes a LoginViewController as the first argument, allowing one object to serve
// as the delegate of many LoginViewControllers
- (void)loginViewControllerDidLoginSuccessfully:(LoginViewController *)lvc;
- (void)loginViewController:(LoginViewController *)lvc didFailWithError:(NSError *)error;
- (void)loginViewControllerDidReceivePasswordResetRequest:(LoginViewController *)lvc;
- (void)loginViewControllerDiDReceiveSignupRequest:(LoginViewController *)lvc;
- (BOOL)loginViewControllerShouldAllowAnonymousLogin:(LoginViewController *)lvc;

@end

登录控制器可以向它的委托传递一些事件,以及向它的委托询问用于自定义其行为的信息。它在其实现中将事件传达给委托,作为其对用户操作的响应的一部分:

#import "LoginViewController.h"

@interface LoginViewController ()

@property (weak, nonatomic) IBOutlet UIButton *anonSigninButton;

@end

@implementation LoginViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    //  Here we ask the delegate for information used to layout the view
    BOOL anonymousLoginAllowed = NO;
    //  All our protocol methods are @optional, so we must check they are actually implemented before calling.
    if ([self.delegate respondsToSelector:@selector(loginViewControllerShouldAllowAnonymousLogin:)]) {
        // self is passed as the LoginViewController argument to the delegate methods
        // in this way our delegate can serve as the delegate of multiple login view controllers, if needed
        anonymousLoginAllowed = [self.delegate loginViewControllerShouldAllowAnonymousLogin:self];
    }
    self.anonSigninButton.hidden = !anonymousLoginAllowed;
}

- (IBAction)loginButtonAction:(UIButton *)sender
{
    // We're preteneding our password is always bad. So we assume login succeeds when allowed anonmously
    BOOL loginSuccess = [self isAnonymousLoginEnabled];
    NSError *loginError = [self isAnonymousLoginEnabled] ? nil : [NSError errorWithDomain:@"domain" code:0 userInfo:nil];

    //  Fake concurrency
    double delayInSeconds = 1.0;
    dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
    dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
        //  Notify delegate of failure or success
        if (loginSuccess) {
            if ([self.delegate respondsToSelector:@selector(loginViewControllerDidLoginSuccessfully:)]) {
                [self.delegate loginViewControllerDidLoginSuccessfully:self];
            }
        }
        else {
            if ([self.delegate respondsToSelector:@selector(loginViewController:didFailWithError:)]) {
                [self.delegate loginViewController:self didFailWithError:loginError];
            }
        }
    });
}

- (IBAction)forgotPasswordButtonAction:(id)sender
{
    //  Notify delegate to handle forgotten password request.
    if ([self.delegate respondsToSelector:@selector(loginViewControllerDidReceivePasswordResetRequest:)]) {
        [self.delegate loginViewControllerDidReceivePasswordResetRequest:self];
    }
}

- (IBAction)signupButtonAction:(id)sender
{
    //  Notify delegate to handle signup request.
    if ([self.delegate respondsToSelector:@selector(loginViewControllerDiDReceiveSignupRequest:)]) {
        [self.delegate loginViewControllerDiDReceiveSignupRequest:self];
    }
}

- (BOOL)isAnonymousLoginEnabled
{
    BOOL anonymousLoginAllowed = NO;

    if ([self.delegate respondsToSelector:@selector(loginViewControllerShouldAllowAnonymousLogin:)]) {
        anonymousLoginAllowed = [self.delegate loginViewControllerShouldAllowAnonymousLogin:self];
    }
    return  anonymousLoginAllowed;
}

@end

主视图控制器实例化并呈现一个登录视图控制器,并处理其委托消息:

#import "MainViewController.h"
#import "LoginViewController.h"

#define LOGGED_IN NO

@interface MainViewController () <LoginViewControllerDelegate>

@end

@implementation MainViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    //  Fake loading time to show the modal cleanly
    if (!LOGGED_IN) {
        double delayInSeconds = 1.0;
        dispatch_time_t popTime = dispatch_time(DISPATCH_TIME_NOW, (int64_t)(delayInSeconds * NSEC_PER_SEC));
        dispatch_after(popTime, dispatch_get_main_queue(), ^(void){
            //  Create a login view controller, assign its delegate, and present it
            LoginViewController *lvc = [[LoginViewController alloc] init];
            lvc.delegate = self;
            [self presentViewController:lvc animated:YES completion:^{
                NSLog(@"modal completion finished.");
            }];
        });
    }
}

#pragma mark - LoginViewControllerDelegate


- (void)loginViewControllerDidLoginSuccessfully:(LoginViewController *)lvc
{
    NSLog(@"Login VC delegate - Login success!");
    [self dismissViewControllerAnimated:YES completion:NULL];
}

- (void)loginViewController:(LoginViewController *)lvc didFailWithError:(NSError *)error
{
    // Maybe show an alert...
    // UIAlertView *alert = ...
}

- (void)loginViewControllerDidReceivePasswordResetRequest:(LoginViewController *)lvc
{
    // Take the user to safari to reset password maybe
     NSLog(@"Login VC delegate - password reset!");
}

- (void)loginViewControllerDiDReceiveSignupRequest:(LoginViewController *)lvc
{
    // Take the user to safari to open signup form maybe
    NSLog(@"Login VC delegate - signup requested!");
}

- (BOOL)loginViewControllerShouldAllowAnonymousLogin:(LoginViewController *)lvc
{
    return YES;
}

@end

在某些方面登录可能是一个复杂的交互式过程,因此我建议您认真考虑使用授权而不是通知。但是,可能有问题的一件事是委托必须只是一个对象。如果您需要让多个不同的对象知道登录视图控制器的进度和状态,那么您可能需要使用通知。尤其是如果登录过程可以被限制为非常简单,以一种除了传递单向消息和数据之外不需要任何交互的方式,那么通知可以成为一种可行的选择。您可以在userInfo 属性内的通知中将任意变量传递回,该属性是您决定在其中填充的任何内容的NSDictionary。通知会影响性能,但我知道现在只有当观察者达到数百人时才会发生这种情况。尽管如此,这在我看来并不是最合适的,因为您有父对象(或多或少控制子对象的生命周期)向第三方对象请求子对象的更新。

【讨论】:

  • 哇,非常感谢您抽出宝贵时间为我提供如此详尽的解释。我现在对创建委托以及何时使用委托有了更多的了解。非常感谢!
  • 我注意到您的所有代表都返回了自己。所有代表通常都会返回自己吗?
  • @Alan,他们实际上并没有返回self,而是将self 作为参数传递给方法。您经常会看到委托协议在其方法中具有用于委托对象的参数。以UITableViewDelegate 为例,每个方法的第一个参数都是UITableView。委托对象在委托方法调用中传递自己,以便委托可以充当多个此类对象的委托,并且可以区分谁在调用该方法。顺便说一句,这是一个很好的问题,我应该明确地将其添加到我的答案中。
  • 啊太棒了!谢谢卡尔!
  • 如果我必须通过多个视图控制器才能在模态视图中获取用户输入,我该如何使用上述内容,其中模态视图是 UINavigationController?
猜你喜欢
  • 1970-01-01
  • 2012-10-23
  • 1970-01-01
  • 1970-01-01
  • 2018-12-23
  • 2020-04-01
  • 2017-01-10
  • 2016-03-21
  • 1970-01-01
相关资源
最近更新 更多