Value Transfer Between iOS pages (Delegate/NSNotification/Block/NSUserDefault/Singleton), iosnsnotification

Source: Internet
Author: User

Value Transfer Between iOS pages (Delegate/NSNotification/Block/NSUserDefault/Singleton), iosnsnotification

 

How to pass values between iOS pages (NSUserDefault/Delegate/NSNotification/Block/Singleton)

The following values are passed between iOS pages: 1. delegate the delegate method; 2. notification method; 3. block Method; 4. userDefault or file method; 5. singleton mode; 6. set Properties to pass values between pages

During iOS development, we often encounter the issue of jump between pages to transfer values. Here we will summarize:

Scenario 1: page A jumps to page B

Method:

In the controller of page B, write the corresponding attributes, jump to the location of page B on page A, and assign values to the attributes of page B.

//SecondViewController.h

@ Property (nonatomic) NSInteger flag; // The Current System ID (0: other value passing methods; 1: block Value passing methods)

In the attempt controller of page

 

//RootViewController.m

- (IBAction)showSecondView:(id)sender { SecondViewController *second = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil]; second.delegate = self; second.flag = 0; [self presentViewController:second animated:YES completion:nil];}

 

Case 2: page A jumps to page B, and page B jumps back to page

Mainstream solutions:

(1) implemented by entrusting delegate

 

SET protocols and Methods
 
//SecondViewController.h

@protocol secondViewDelegate-(void)showName:(NSString *)nameString;@end

 

Set proxy (to prevent loop reference, weak is used here)

 

 
//SecondViewController.h

@interface SecondViewController : UIViewController@property (nonatomic, weak)id<secondViewDelegate> delegate;@property (nonatomic, copy) ablock block;@end
Call
//SecondViewController.m
- (IBAction)delegateMethod:(id)sender { if ([self notEmpty]) { [self.delegate showName:self.nameTextField.text]; [self dismissViewControllerAnimated:YES completion:nil]; }else{ [self showAlert]; }}

Display
//RootViewController.m
-(void)showName:(NSString *)nameString{ self.nameLabel.text = nameString;}

 

The most important and easy to ignore is to set the delegate point.

(2) notification

In the controller of page B, send a notification:
//SecondViewController.m- (IBAction)notificationMethod:(id)sender {    if ([self notEmpty]) {        [[NSNotificationCenter defaultCenter] postNotificationName:@"ChangeNameNotification" object:self userInfo:@{@"name":self.nameTextField.text}];        [self dismissViewControllerAnimated:YES completion:nil];    }else{        [self showAlert];    }}

 

Register the notification in the Controller on page:

//RootViewController.m- (void)viewDidLoad{    [super viewDidLoad];    // Do any additional setup after loading the view from its nib.    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ChangeNameNotification:) name:@"ChangeNameNotification" object:nil];}

Remember to delete the notification when we do not use it:

//RootViewController.m-(void)dealloc{    [[NSNotificationCenter defaultCenter] removeObserver:self];}

 

Call, display

//RootViewController.m-(void)ChangeNameNotification:(NSNotification*)notification{    NSDictionary *nameDictionary = [notification userInfo];    self.nameLabel.text = [nameDictionary objectForKey:@"name"];}

 

(3) block implementation

Block Introduction: http://blog.csdn.net/totogo2010/article/details/7839061

A very interesting article describing block callback: http://blog.csdn.net/mobanchengshuang/article/details/11751671

Analysis:

In B's attempt to control a block, the parameter is a string

//SecondViewController.htypedef void (^ablock)(NSString *str);
//SecondViewController.h@property (nonatomic, copy) ablock block;

In B's attempt controller, after entering the name and clicking the corresponding OK button

- (IBAction)blockMethod:(id)sender {    if ([self notEmpty]) {        if (self.block) {            self.block(self.nameTextField.text);            [self dismissViewControllerAnimated:YES completion:nil];        }    }else{        [self showAlert];    }}

When A tries to display, the callback block

- (IBAction)showSecondWithBlock:(id)sender {    SecondViewController *second = [[SecondViewController alloc] initWithNibName:@"SecondViewController" bundle:nil];    [self presentViewController:second animated:YES completion:nil];    second.block = ^(NSString *str){        self.nameLabel.text = str;    };}

 

 

I also saw the following solutions when I checked the materials:

(1) Use SharedApplication to define a variable for transmission (feeling the same way as Singleton)

 

(2) Use a file or NSUserdefault to pass

 

// Store values in the file or UserDefault mode (this method is not suitable for storing values in the file or UserDefault mode)-(IBAction) userDefaultMethod :( id) sender {if ([self notEmpty]) {[[NSUserDefaults standardUserDefaults] setObject: self. nameTextField. text forKey: @ "myNameText"]; [self dismissViewControllerAnimated: YES completion: nil];} else {[self showAlert];}

When A tries to display controller

-(Void) viewDidAppear :( BOOL) animated {[super viewDidAppear: animated]; // if you want to test data passing through UserDefault or using Singleton, cancel the following comments to/* if ([[NSUserDefaults standardUserDefaults] objectForKey: @ "myNameText"] length]! = 0) {self. nameLabel. text = [[NSUserDefaults standardUserDefaults] objectForKey: @ "myNameText"]; [[NSUserDefaults standardUserDefaults] setObject: @ "forKey: @" myNameText "];} dataSource * dataSource = [DataSource sharedDataSource]; if ([dataSource. myName length]! = 0) {self. nameLabel. text = dataSource. myName; dataSource. myName = @"";}*/}

 

(3) passing through a singleton class

B tries to Controller

// Pass the value through the singletonMethod (this method is not suitable for this type of value transfer. If you want to use the singletonMethod, you can consider this method)-(IBAction) singletonMethod :( id) sender {if ([self notEmpty]) {DataSource * dataSource = [DataSource sharedDataSource]; dataSource. myName = self. nameTextField. text; [self dismissViewControllerAnimated: YES completion: nil];} else {[self showAlert] ;}}

A tries to display the Controller

-(Void) viewDidAppear :( BOOL) animated {[super viewDidAppear: animated]; // if you want to test data passing through UserDefault or using Singleton, cancel the following comments to/* if ([[NSUserDefaults standardUserDefaults] objectForKey: @ "myNameText"] length]! = 0) {self. nameLabel. text = [[NSUserDefaults standardUserDefaults] objectForKey: @ "myNameText"]; [[NSUserDefaults standardUserDefaults] setObject: @ "forKey: @" myNameText "];} dataSource * dataSource = [DataSource sharedDataSource]; if ([dataSource. myName length]! = 0) {self. nameLabel. text = dataSource. myName; dataSource. myName = @ "";} */} @ end

The Singleton mode is used here. The DataSource class is compiled to store data.

/// DataSource. h // TestCallBack /// Created by csdc-iMac on 14-7-17. // Copyright (c) 2014 JuneWang. all rights reserved. // # import <Foundation/Foundation. h> @ interface DataSource: NSObject @ property (nonatomic, strong) NSString * myName; + (DataSource *) sharedDataSource; @ end

 

/// DataSource. m // TestCallBack /// Created by csdc-iMac on 14-7-17. // Copyright (c) 2014 JuneWang. all rights reserved. // # import "DataSource. h "@ implementation DataSource + (DataSource *) sharedDataSource {static DataSource * dataSource = nil; static dispatch_once_t once; dispatch_once (& once, ^ {dataSource = [DataSource new];}); return dataSource;} @ end

 

Program running

A View:

B View

When you enter A name and click the corresponding confirmation button, the system returns to view A and displays the name entered in view B.

 

I wish you a good time. please correct me if you have any other or incorrect solutions.

If it is not detailed, you can use the source code analysis.

 

Reference: http://blog.csdn.net/cocoarannie/article/details/11857141

Http://www.cnblogs.com/heri/archive/2013/03/18/2965815.html

 

Source Code address: https://github.com/wangtao169447/PassValue

Reprinted please indicate the source: http://www.cnblogs.com/JuneWang/p/3850859.html


The block in iOS can replace delegate

Yes !, If the value is simple, block is good.

How does one pass the value on the IOS page?

Little cainiao, 1 custom cell, add attribute to cell

2. delegate for Minor Use

3 block

A demo is required for this broken object?
 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.