SoFunction
Updated on 2025-04-08

Talk about iOS singleton mode

Singleton mode is a commonly used software design mode. Its core structure contains only one special class called a singleton. Through the singleton mode, it can be ensured that there is only one instance of a class in the system and that the instance is easy to access from the outside world, thereby facilitating the control of the number of instances and saving system resources. If you want only one object of a certain class in the system, singleton pattern is the best solution.

1. Writing steps

1) Create a class method and return an object instance. Start with shared default current.
2) Create a global variable to save the object's reference
3) Determine whether the object exists. If it does not exist, create the object

2. Several modes of specific singleton mode

The first singleton mode

//Non-thread-safe writing
static UserHelper * helper = nil;

+ (UserHelper *)sharedUserHelper {

if (helper == nil) {

helper = [[UserHelper alloc] init];

}

 return helper;

}

The second singleton mode

//Thread safety writing method 1
static UserHelper * helper = nil;

+ (UserHelper *)sharedUserHelper {

 @synchronized(self) {

  

  if (helper == nil) {

   helper = [[UserHelper alloc] init];

  }

 }

 return helper;

}

The third singleton mode 

+ (void)initialize {

 

 if ([self class] == [UserHelper class]) {

  helper = [[UserHelper alloc] init];

 }

}

The fourth singleton mode

//Thread safety writing method 3 (Apple recommends it mainly to use this)
static UserHelper * helper = nil;

+ (UserHelper *)sharedUserHelper {

 

static dispatch_once_t onceToken;

 dispatch_once(&onceToken, ^{

  helper = [[UserHelper alloc] init];

 });

 

 return helper;

}

MRC fully implements singleton writing (understand)

#import <Foundation/>

#import ""

 

void func() {

 

 static dispatch_once_t onceToken;

 dispatch_once(&onceToken, ^{

 NSLog(@"haha");

 });

}

 

int main(int argc, const char * argv[]) {

 @autoreleasepool {

 

// [UserHelper logout];

 

 if ([UserHelper isLogin]) {

  

  UserHelper * helper = [UserHelper sharedUserHelper];

  NSLog(@"username = %@ password = %@",,);

  

 } else {

  

  char name[20];

  char pwd[20];

  NSLog(@"Please enter a username");

  scanf("%s",name);

  NSLog(@"Please enter your password");

  scanf("%s",pwd);

  

  NSString * userName = [[NSString alloc] initWithUTF8String:name];

  NSString * password = [[NSString alloc] initWithUTF8String:pwd];

  

  if (userName && password) {

  

  [UserHelper loginWithUserName:userName password:password];

  

  UserHelper * helper = [UserHelper sharedUserHelper];

  NSLog(@"username = %@ password = %@",,);

  

  }

 }

 

// UserHelper * help1 = [UserHelper sharedUserHelper];

//  = @"dahuan";

//  = @"123456";

// NSLog(@"%p",help1);

// NSLog(@"%@",);

// NSLog(@"%@",);

//

// 

// UserHelper * help2 = [UserHelper sharedUserHelper];

//  = @"zxc";

// NSLog(@"%p",help2);

// NSLog(@"%@",);

// NSLog(@"%@",);

 

 }

 return 0;

}

 //

#import <Foundation/>

 

@interface UserHelper : NSObject

 

//1. Create a class method and return an object instance shared default current
 

+ (UserHelper *)sharedUserHelper;

 

@property (nonatomic, copy) NSString * userName;

 

@property (nonatomic, copy) NSString * password;

 

+ (BOOL)isLogin;

 

+ (void)loginWithUserName:(NSString *)userName password:(NSString *)password;

 

+ (void)logout;

 

@end

 

// 

#import ""

 

//2. Create a global variable
 

#define Path @"/Users/dahuan/Desktop/data"

 

static UserHelper * helper = nil;

 

@implementation UserHelper

 

//+ (void)initialize {

// 

// if ([self class] == [UserHelper class]) {

// helper = [[UserHelper alloc] init];

// }

//}

 

+ (UserHelper *)sharedUserHelper {

 

 //3. Determine whether the object exists. If it does not exist, create the object
 //Thread safety
// @synchronized(self) {

// 

// if (helper == nil) {

//  helper = [[UserHelper alloc] init];

// }

// }

 

 //gcd thread safety
 static dispatch_once_t onceToken;

 dispatch_once(&onceToken, ^{

 helper = [[UserHelper alloc] init];

 });

 

 return helper;

}

 

- (instancetype)init {

 

 if (self = [super init]) {

 

 NSString * data = [NSString stringWithContentsOfFile:Path encoding:NSUTF8StringEncoding error:nil];

 if (data) {

  NSArray * array = [data componentsSeparatedByString:@"-"];

  _userName = array[0];

  _password = array[1];

 }

 }

 return self;

}

 

+ (BOOL)isLogin {

 

 UserHelper * helper = [UserHelper sharedUserHelper];

 if ( && ) {

 return YES;

 }

 return NO;

}

 

+ (void)loginWithUserName:(NSString *)userName password:(NSString *)password {

 

 UserHelper * helper = [UserHelper sharedUserHelper];

  = userName;

  = password;

 

 NSArray * array = @[userName,password];

 NSString * data = [array componentsJoinedByString:@"-"];

 [data writeToFile:Path atomically:YES encoding:NSUTF8StringEncoding error:nil];

}

 

+ (void)logout {

 

 NSFileManager * fm = [NSFileManager defaultManager];

 

 if ([fm fileExistsAtPath:Path]) {

 [fm removeItemAtPath:Path error:nil];

 }

}

 

@end

The above is all about iOS singleton mode, I hope it will be helpful to everyone's learning.