将数据传递回上一个viewcontroller

Ant*_*ony 53 iphone objective-c uiviewcontroller ios

我正在尝试将数据传递回以前的viewController.

有谁知道如何将数据从ViewController B传递回ViewController A?所以我想要一个字符串'从'BIDAddTypeOfDealViewController转到BIDDCCreateViewController.用户编辑了viewController B,我想在ViewController A中返回已编辑的数据然后我使用它.

我正在使用此答案的"传递数据"部分.我的不同之处:第3点和第6点只是在弹出视图时提及,所以我将该代码放在viewWillDisappear中.我认为这是正确的吗?同样在Point 6,我没有使用nib进行初始化,因为它已经过时了.我正在使用故事板.而且我没有添加最后一行,因为我不相信我会推动它.按我的故事板上的按钮已经让我前进了.

我认为问题可能出现在BIDDCCreateViewController中,我有方法,但我无法运行它.要运行一个方法,它应该[自我方法].我无法做到这一点.那就是我猜的.

它编译并运行良好,没有任何记录,所以我不知道它是否有效.

更新:我无法获得'sendDataToA'方法来执行.

#import <UIKit/UIKit.h>
#import "BIDAddTypeOfDealViewController.h"

 @interface BIDDCCreateViewController : UIViewController
 @property (strong, nonatomic) NSString *placeId;
- (IBAction)gotoBViewController:(id)sender;
@end


#import "BIDDCCreateViewController.h"
#import "BIDAddTypeOfDealViewController.h"

@implementation BIDDCCreateViewController

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    NSLog(@"SUCCESSFULLY PASSED PLACE ID: %@", self.placeId);
}

-(void)sendDataToA:(NSString *)myStringData
{

    NSLog(@"Inside sendDataToA");
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"Your string Data Showing" message:myStringData delegate:self cancelButtonTitle:@"Ok " otherButtonTitles:nil];
    [alert show];
}

- (IBAction)gotoBViewController:(id)sender {
    NSLog(@"pressed");
    BIDAddTypeOfDealViewController *bidAddType = [[BIDAddTypeOfDealViewController alloc]init];
    bidAddType.delegate = self;

}
@end


@protocol senddataProtocol <NSObject>
-(void)sendDataToA:(NSString *)myStringData;
@end

#import <UIKit/UIKit.h>
@interface BIDAddTypeOfDealViewController : UIViewController <UITextFieldDelegate>//Using this delegate for data a user inputs
@property(nonatomic,assign)id delegate;
//other textfield outlets not relevant
- (IBAction)chooseDiscountDeal:(id)sender;
@end

#import "BIDAddTypeOfDealViewController.h"

@interface BIDAddTypeOfDealViewController ()

@end

@implementation BIDAddTypeOfDealViewController
@synthesize delegate;

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)viewDidLoad
{
    [super viewDidLoad];
}

-(void)viewWillDisappear:(BOOL)animated
{
    [delegate sendDataToA:@"Apple"];
}
@end
Run Code Online (Sandbox Code Playgroud)

Erh*_*rci 93

您可以使用代理人.因此,在ViewController B中,您需要创建一个将数据发送回ViewController A的协议.您的ViewController A将成为ViewController B的委托.

如果您不熟悉目标C,请查看什么是代表.

在ViewControllerB.h中创建协议:

#import <UIKit/UIKit.h>

@protocol senddataProtocol <NSObject>

-(void)sendDataToA:(NSArray *)array; //I am thinking my data is NSArray, you can use another object for store your information. 

@end

@interface ViewControllerB : UIViewController

@property(nonatomic,assign)id delegate;
Run Code Online (Sandbox Code Playgroud)

ViewControllerB.m

@synthesize delegate;
-(void)viewWillDisappear:(BOOL)animated
{
     [delegate sendDataToA:yourdata];

}
Run Code Online (Sandbox Code Playgroud)

在ViewControllerA中:当你转到ViewControllerB时

ViewControllerA *acontollerobject=[[ViewControllerA alloc] initWithNibName:@"ViewControllerA" bundle:nil];
acontollerobject.delegate=self; // protocol listener
[self.navigationController pushViewController:acontollerobject animated:YES];
Run Code Online (Sandbox Code Playgroud)

并定义你的功能:

-(void)sendDataToA:(NSArray *)array
{
   // data will come here inside of ViewControllerA
}
Run Code Online (Sandbox Code Playgroud)

编辑:

您可以查看此示例:如何将数据传递回上一个viewcontroller:Tutorial链接

  • 这个答案是错误的,因为它在viewcontrollerA中需要这个:@property(nonatomic,weak)id <senddataProtocol> delegate; (2认同)

Hei*_*sch 54

短和更简单的比协议/委托方法是创建一个闭合:

用于在我的情况下发回一个字符串.在ViewControllerA中:

override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
    if let viewControllerB = segue.destination as? ViewControllerB {
        viewControllerB.callback = { message in
            //Do what you want in here!
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

在ViewControllerB中:

var callback : ((String) -> Void)?

@IBAction func done(sender: AnyObject) {
    callback?("Hi")
    self.dismiss(animated: true, completion: nil)
}
Run Code Online (Sandbox Code Playgroud)

  • 我也想用这个 - 它很快。但我也担心闭包中的内存泄漏问题。要解决闭包中的泄漏,您不能直接使用 `"self"`。必须先创建一个弱自我/无主自我,然后将其转换为强自我,然后才能在闭包中使用它。 (2认同)

Sur*_*gch 40

Swift:使用委托模式发回数据

我的覆盖数据传递两种方式充分的答案是在这里.我在这里解释代表模式的答案.

要将数据从第二个视图控制器传回第一个视图控制器,请使用协议和委托.这个视频是一个非常清晰的过程:

以下是基于视频的示例(稍作修改).

在此输入图像描述

在Interface Builder中创建故事板布局.再次,要制作segue,只需Control从按钮拖动到第二视图控制器即可.将segue标识符设置为showSecondViewController.另外,不要忘记使用以下代码中的名称来连接出口和操作.

第一视图控制器

第一视图控制器的代码是

import UIKit

class FirstViewController: UIViewController, DataEnteredDelegate {

    @IBOutlet weak var label: UILabel!

    override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?) {
        if segue.identifier == "showSecondViewController" {
            let secondViewController = segue.destinationViewController as! SecondViewController
            secondViewController.delegate = self
        }
    }

    func userDidEnterInformation(info: String) {
        label.text = info
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意我们的自定义DataEnteredDelegate协议的使用.

第二视图控制器和协议

第二个视图控制器的代码是

import UIKit

// protocol used for sending data back
protocol DataEnteredDelegate: class {
    func userDidEnterInformation(info: String)
}

class SecondViewController: UIViewController {

    // making this a weak variable so that it won't create a strong reference cycle
    weak var delegate: DataEnteredDelegate? = nil

    @IBOutlet weak var textField: UITextField!

    @IBAction func sendTextBackButton(sender: UIButton) {

        // call this method on whichever class implements our delegate protocol
        delegate?.userDidEnterInformation(textField.text!)

        // go back to the previous view controller
        self.navigationController?.popViewControllerAnimated(true)
    }
}
Run Code Online (Sandbox Code Playgroud)

请注意,protocol它位于View Controller类之外.

而已.现在运行应用程序,您应该能够将数据从第二个视图控制器发送回第一个.

  • 委托是可选的,因此它有可能是零.[可选类的默认初始化值为nil](http://stackoverflow.com/q/24065442/3681880)已经存在,但在我看来,明确说明它更清楚.有关使用委托的更多说明,请参阅[此答案](http://stackoverflow.com/a/34566876/3681880). (4认同)