美文网首页
Objective-C页面之间传递数据

Objective-C页面之间传递数据

作者: Jixin | 来源:发表于2018-04-12 00:27 被阅读124次

    stackoverflow上关于Objective-C关注度比较高的问题系列
    链接

    页面之间传递数据

    原文链接《Passing Data between View Controllers》
    本文Github链接,含代码

    关键词

    Passing Data between View Controllers
    Delegate
    Block
    NSUserDefaults
    Singleton
    NSNotification

    1.向下一个页面传递数据

    Passing Data Forward

    从页面A通过navitagion push进入页面B,此时需要传递数据(这个数据可以是object或者value)给页面B,可以用下面这个方法。

    有两个ViewController:ViewControllerAViewControllerB,需用从ViewControllerA传递一个字符串ViewControllerB.

    1. ViewControllerB中添加一个NSString类型的property title
    @property (nonatomic, copy) NSString *title;
    
    
    1. ViewControllerA 中你需要导入ViewControllerB
    #import "ViewControllerB.h"
    

    然后在你需要pushViewControllerB之前给ViewControllerBpropetytitle赋值

    ViewControllerB *viewControllerB = [[ViewControllerB alloc] init];
    viewControllerB.title = @"The second View";
    [self.navigationController pushViewController:viewControllerB animated:YES];
    
    

    2.通过Segues进入下个页面的传递数据

    Passing Data Forward using Segues

    如果你使用了Storyboards,那么很大可能会用到segue来push页面。这里的数据传递和上面中的数据传递类似,在push页面之前下面这个方法会被调用

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
    
    

    所以从ViewControllerA传递一个字符串ViewControllerB的步骤应如下:

    1. ViewControllerB中添加一个NSString类型的property title
    @property (nonatomic, copy) NSString *title;
    
    
    1. ViewControllerA 中你需要导入ViewControllerB
    #import "ViewControllerB.h"
    
    1. 在Storyboard中创建一个从ViewControllerAViewControllerB的segue,并且给这个segue一个identifier,例如"showDetailSegue"

    2. ViewControllerA添加-(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender方法,此方法会在任何使用segue进行转场时被调用(响应)。其中segue就是storyBoard转场控制对象,在参数segue中能够获取所要跳转的试图控制器,destinationViewController(目标vc),sourceViewController(源视图vc)。

    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
        if([segue.identifier isEqualToString:@"showDetailSegue"]){
            ViewControllerB *viewControllerB = (ViewControllerB *)segue.destinationViewController;        
            viewControllerB.title = @"The second View";
        }
    }
    
    

    如果你的ViewControllerB是嵌入在一个NavigationController中那么需要使用下面这个方法来获取ViewControllerB

    
    -(void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
        if([segue.identifier isEqualToString:@"showDetailSegue"]){
            UINavigationController *navController = (UINavigationController *)segue.destinationViewController;
            ViewControllerB * viewControllerB = (ViewControllerB *)navController.topViewController;
            viewControllerB.title = @"The second View";
        }
    }
    
    

    3.向上一个页面传递数据

    Passing Data Back

    ViewControllerBViewControllerA回传数据,你可以使用Protocol和delegate 或者是 Block。后者可以作为一种低耦合的回调机制

    Protocol and Delegate 方式

    我们将使ViewControllerAViewControllerB的一个delegate(代理)。这样可以允许ViewControllerB发送一个message回传给ViewControllerB,从而实现回传数据。

    要想使ViewControllerAViewControllerB的一个delegate,ViewControllerA必须(conform)遵从ViewControllerB的protocol(协议)。此协议将告诉ViewControllerA哪些方法是必须要实现的。

    1. ViewControllerB中,在#import@interface之间你需要具体说明你的协议,代码如下:
    
    @class ViewControllerB;
    
    @protocol ViewControllerBDelegate <NSObject>
    
    - (void)viewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)content;
    
    @end
    
    
    1. 接下来还是在ViewControllerB中,你需要给ViewContollerB添加一个delegate属性,然后在.msynthesize
    @property (nonatomic, weak) id<ViewControllerBDelegate> delegate;
    
    
    1. ViewControllerB中当我们需要传递数据给ViewControllerA时,调用delegate的方法。通常在点击button或者页面pop的时候。
    
    - (IBAction)backButtonClicked:(id)sender {
        NSString *content = @"Pass this value back to ViewControllerA";
        if ([self.delegate respondsToSelector:@selector(viewController:didFinishEnteringItem:)]) {
            [self.delegate viewController:self didFinishEnteringItem:content];
        }
    }
    
    
    1. 以上ViewControllerB部分就完成了,接下来在ViewControllerA中,导入ViewControllerB.h并且遵从它的协议。
    #import "ViewControllerB.h"
    
    @interface ViewControllerA ()<ViewControllerBDelegate>
    
    @end
    
    
    1. ViewControllerA中实现ViewControllerBDelegate的方法。
    #pragma mark - ViewControllerBDelegate
    
    - (void)viewController:(ViewControllerB *)controller didFinishEnteringItem:(NSString *)content {
        NSLog(@"This was returned from ViewControllerB %@", content);
    }
    
    
    1. 在push进入ViewControllerB之前,你需要告诉ViewControllerB,它的delegateViewControllerA
    ViewControllerB *viewControllerB = [[ViewControllerB alloc] init];
    viewControllerB.delegate = self
    [self.navigationController pushViewController:viewControllerB animated:YES];
    
    

    Block 方式

    我们将在ViewControllerA中给ViewControllerB的block赋值,当在ViewControllerB调用block时,ViewControllerA中block将响应,并执行block中的操作。

    1. ViewControllerB.h中添加一个block属性
    @property (nonatomic, copy) void (^block)(NSString *content);
    
    
    1. ViewControllerB.m中,当我们需要传递数据给ViewControllerA时,调用block。通常在点击button或者页面pop的时候。
    - (IBAction)backButtonClicked:(id)sender {
        NSString *content = @"Pass this value back to ViewControllerA";
        if (self.block) {
            self.block(content);
        }
    }
    
    1. 在push进入ViewControllerB之前,你需要给ViewControllerB的block赋值。特别注意,在此处block中,如果要使用self的话,需要使用weakSelf,这样能够防止循环引用。具体代码如下:
    ViewControllerB *viewControllerB = [[ViewControllerB alloc] init];
    __weak __typeof__ (self)weakSelf = self;
    viewControllerB.block = ^(NSString *content) {
        NSLog(@"This was returned from ViewControllerB %@", content);
        weakSelf.tipLabel.text = content;
    };
    [self.navigationController pushViewController:viewControllerB animated:YES];
    

    4.跨页面的数据传递

    有时候传递数据的两个页面并非相互紧挨着,有时候数据需要传递给多个页面,那么上述的方法就不太好用了,下面介绍三个跨页面的数据传递: NSUserDefaults, Singleton, NSNotification。

    NSUserDefaults

    官方文档

    简单来说NSUserDefaults是iOS系统提供的一个单例类(iOS提供了若干个单例类),通过类方法standardUserDefaults可以获取NSUserDefaults单例,可以读写一下几类数据。

    NSData
    NSString
    NSNumber(BOOL, integer, float, double)
    NSDate
    NSArray
    NSDictionary
    NSURL
    

    使用NSUserDefaults很简单,在需要存储的地方写入数据,在需要使用的地方读取数据。当APP重新启动,版本更新,所存储的数据都不会丢失;但是如果将APP卸载了,存储在NSUserDefaults中的数据就会被一并删除。

    1. 写入
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    [userDefaults setObject:@"This string was in NSUserDefaults." forKey:@"kPassingDataBetweenViewControllers"];
    [userDefaults synchronize];
    
    
    1. 读取
    NSUserDefaults *userDefaults = [NSUserDefaults standardUserDefaults];
    NSString *content = [userDefaults objectForKey:@"kPassingDataBetweenViewControllers"];
    self.userDefaultsLabel.text = content;
    

    Singleton 单例

    Singleton 会阻止其他对象实例化其自己的 Singleton 对象的副本,从而确保所有对象都访问唯一实例。单例一旦被创建,在APP的整个生命周期内都不会被销毁(如果没有手动销毁的话)。所以单例可以用来存储数据。

    1. 创建一个基于NSObject的文件,PassingDataManager。在.h中添加需要存储数据的属性和一个类方法(用于向整个系统提供这个实例)。
    @interface PassingDataManager : NSObject
    
    @property (nonatomic, copy) NSString *content;
    
    + (instancetype)sharedManager;
    
    @end
    
    1. .m
    + (instancetype)sharedManager {
        static PassingDataManager *manager = nil;
        static dispatch_once_t onceToken;
        dispatch_once(&onceToken, ^{
            manager = [[PassingDataManager alloc] init];
        });
        return manager;
    }
    
    

    单例不能放在堆区(控制器A死了,里面创建的对象也死了),在任何需要的地方的都能拿到,因此放到静态区(静态区内部的对象只要一创建,它的声明周期就和app 一样)

    1. 在需要给其赋值的地方,需要#import "PassingDataManager.h"
    [PassingDataManager sharedManager].content = @"This message come from Singleton";
    
    1. 在需要取值的地方,需要#import "PassingDataManager.h"
    self.singletonLabel.text = [PassingDataManager sharedManager].content;
    

    NSNotification 通知

    使用通知可以在一处发送,多处接收。

    1. 在需要添加通知的地方(接收数据处)添加通知,并且添加处理通知的方法
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(handleData:) name:@"kPassingDataBetweenViewControllersNotification" object:nil];
    
    #pragma mark - Notification
    
    - (void)handleData:(NSNotification *)notification {
        NSDictionary *info = notification.object;
        NSString *content = [info valueForKey:@"content"];
        self.title = content;
    }
    
    
    1. 在发送通知的地方(发送数据处)
    NSDictionary *info = @{@"content" : @"Notification"};
        [[NSNotificationCenter defaultCenter] postNotificationName:@"kPassingDataBetweenViewControllersNotification" object:info];
    
    
    1. 在需要添加通知的地方(接收数据处),当对象销毁前需要将该对象注册的通知移除掉,否则,程序会crash。
    - (void)dealloc {
        [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
    
    

    5.总结

    页面见传递数据的方法有如下几点:

    1. 在alloc一个class之后初始化该class的属性;
    2. Delegate;
    3. Block;
    4. NSUserDefaults,此处可以延伸为数据持久化:plist, SQLite3, CoreData。
    5. Singleton;
    6. NSNotification

    相关文章

      网友评论

          本文标题:Objective-C页面之间传递数据

          本文链接:https://www.haomeiwen.com/subject/cuptkftx.html