码迷,mamicode.com
首页 > 移动开发 > 详细

IOS开发笔记(2)页面之间传递数据几种方式比较

时间:2015-06-05 19:50:03      阅读:126      评论:0      收藏:0      [点我收藏+]

标签:

今天分享一下页面之间传值的几种方式

1、@property属性

这个不用多说了吧,当页面A 跳转到页面B,在class B中声明属性

@property (nonatomic, copy) NSString *name;  

初始化B

FirstViewController *firstVC = [FirstViewController new];
firstVC.name = @"name";
[self presentViewController:firstVC animated:YES completion:nil];

2、Delegate

当页面A 跳转到页面B,B页面返回时传值给A,可以这样实现,在class B中定义一个@protocol,并声明属性delegate;

#import <UIKit/UIKit.h>

@protocol FirstViewControllerDelegate <NSObject>

- (void)print;

@end

@interface FirstViewController : UIViewController

@property (nonatomic, assign) id<FirstViewControllerDelegate> delegate;

@end
.m文件
- (void)backClick:(UIButton *)sender
{
    [self dismissViewControllerAnimated:YES completion:^{
        
        if ([self.delegate respondsToSelector:@selector(print)]) {
            [self.delegate print];
        }
    }];
}
页面A .m实现,要继承FirstViewController的代理

- (void)buttonClicked:(UIButton *)sender
{
    FirstViewController *firstVC = [FirstViewController new];
    firstVC.delegate = self;
    [self presentViewController:firstVC animated:YES completion:nil];
}

#pragma mark - FirstViewControllerDelegate
- (void)print
{
    NSLog(@"delegate response");
}

3、Block

当页面A 跳转到页面B,B页面返回时传值给A,可以这样实现,在class B中定义一个block,并声明属性block

#import <UIKit/UIKit.h>

typedef void (^FirstViewControllerBlock)(NSString *str);

@interface FirstViewController : UIViewController

@property (nonatomic, copy) FirstViewControllerBlock block;

@end
.m文件

- (void)backClick:(UIButton *)sender
{
    self.block(@"first block");
    [self dismissViewControllerAnimated:YES completion:nil];
}
页面A .m实现

- (void)buttonClicked:(UIButton *)sender
{
    FirstViewController *firstVC = [FirstViewController new];
    [self presentViewController:firstVC animated:YES completion:nil];
    firstVC.block = ^(NSString *str) {
        NSLog(@"str is: %@", str);
    };
}

4、NSNotification

IOS开发笔记(2)页面之间传递数据几种方式比较

标签:

原文地址:http://blog.csdn.net/qq510304723/article/details/46380219

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!