单例传值

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

1
2
3
4
5
6
7
#import <FOUNDATION Foundation.h>
  
@interface Session : NSObject
@property (strong,nonatomic) NSString *singleValue;
//实现单例方法
+ (Session *) GetInstance;
@end



1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#import "Session.h"
  
@implementation Session
// 单例对象
static Session *instance;
  
// 单例
+ (Session *) GetInstance {
    @synchronized(self) {
        if (instance == nil) {
            instance = [[self alloc] init];
              
        }
    }
    return instance;
}
-(id) init
{
    if (self = [super init]) {
        self.singleValue = [[NSString alloc] init];
    }
    return self;
}
  
@end



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

Session *session = [Session GetInstance];

session.singleValue = @"好神奇阿!";

NSString *value = session.singleValue;

原文地址:https://www.cnblogs.com/dingfuyan/p/5210051.html