单例传值

//

Ios应用中,不同view及应用中经常会有传值和变量共享,有几种方式可以实现:

1.extern方式

2.单例模式

3.delegate方式

 单例模式顾名思义就是只有一个实例,它确保一个类只有一个实例,并且自行实例化并向整个系统提供这个实例。它经常用来做应用程序级别的共享资源控制。这个模式使用频率非常高,通过一个单例类,可以实现不同view之间的参数传递

 //先建一个Model,继承与NSObject,然后创建单例

#import <Foundation/Foundation.h>

@interface SharedData : NSObject

#pragma mark ----创建单例的方法

//起名习惯: share + 类名

+ (instancetype)shareData;

@property (nonatomic, strong)NSString *inputNssting;

@end

 

 

#import "SharedData.h"

@implementation SharedData

 static SharedData *data = nil;

 //单例类使用此方法,创建单例对象

+ (instancetype)shareData

{

    if (data == nil) {

        //如果没有创建对象,是哟高sharedata 创建新的对象

        data = [[SharedData alloc] init];

    }

    //如果创建了就直接返回创建了的对象

    return data;

}

 @end

 

//使用方法

//这就是某一个控制器的button绑定事件的赋值,想在哪个控制器拿到直接赋值就可以呦,非常简单。

- (void)button1Action:(UIButton *)sender

{

    //然后在需要使用单例的类import 这个单例类

    [SharedData shareData].inputNssting  = self.textField.text;

    SecondViewController *secondVC = [[SecondViewController alloc] init];

   [self.navigationController pushViewController:secondVC animated:YES];

   }

原文地址:https://www.cnblogs.com/lhp-1992/p/4644200.html