效果
首先创建一个单例文件
--------------------------MyData.h-------------------------------
#import <Foundation/Foundation.h>
@interface MyData : NSObject
@property (nonatomic, strong)NSString *name;
+(MyData *) instance;
-----------------------MyData.m-------------------------
#import "MyData.h"
@implementation MyData
static MyData *myData = nil;
+(MyData *) instance {
if(myData==nil){
myData = [[MyData alloc] init];
}
return myData;
}
-----------------设置导航栏左侧按钮(跳转)---------------------------
RootViewController.m
//引用 MyData.h
#import "MyData.h"
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor orangeColor];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"跳转" style:UIBarButtonItemStylePlain target:self action:@selector(jumpPage)];
//创建个单例对象并赋值
MyData *data = [MyData instance];
data.name = @"小明";
}
// 赋值并跳转到第二个页面
-(void) jumpPage {
SecondViewController *second = [[SecondViewController alloc] init];
//Block传值
second.chuanZhiBlock = ^(NSString *str){
// NSLog(@"%@",str);
};
[self.navigationController pushViewController:second animated:YES];
}
-------------------第二个页面处理-----------------------------------
// SecondViewController.h
// UI23Block和单例传值
// Created by focus on 2017/1/23.
// Copyright © 2017年 focus. All rights reserved.
#import <UIKit/UIKit.h>
@interface SecondViewController : UIViewController
//声明Block
@property(nonatomic, copy)void(^chuanZhiBlock)(NSString * Str);
@end
============SecondViewController.m================================
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.view.backgroundColor = [UIColor yellowColor];
self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"返回" style:UIBarButtonItemStylePlain target:self action:@selector(jumpBack)];
MyData *data = [MyData instance];
NSLog(@"获取单例中的Name值:%@", data.name);
}
-(void) jumpBack {
[self.navigationController popViewControllerAnimated:YES];
self.chuanZhiBlock(@"Block传值过来。");
}