preface
What is a singleton?
A class has only one instance (one object), and the instance is easily accessible to the outside world, which conveniently controls the number of instances and saves system resources
To the chase
Singletons are a common pattern in iOS development, but yesterday I went to an interview and was asked an awkward question. Normally in a project we would write a singleton that looks something like this, but now we declare a class method in our.h file
@implementation Singleton+ (instancetype)shareInstance;
@end
Copy the code
And then implement that method in dot m
@implementation Singleton
static Singleton *instance = nil; + (instancetype)shareInstance{
static dispatch_once_t onceToken;
dispath_once(&onceToken,^{
instance = [[self alloc]init];
});
return instance;
}
Copy the code
However, yesterday someone asked the question, saying that it is generally known that this class method creates a singleton, if I don’t know, I just go to the [[self alloc]init] method to create the object. Student: Is there any guarantee that this object class is unique? If you think about it, it seems so. It’s my personal problem too. I didn’t notice this when I was writing the project. At that time it was time I was stumped…… So I wrote a demo and tried it out
single1
single2
single3
Singleton
To solve the problem
So I looked on the Internet, and there are a lot of people who have written tech blogs like this. So I gave it a try. The main thing to do is to ensure that objects are unique, so we need to block the way that users construct objects by alloc and init and copy. When you create an object, there are two main steps: Alloc init 1. We’re going to intercept it after the first alloc. When we call alloc, the OC will call the method allocWithZone to allocate memory, we override this method, and then call the previous class method in this method, return the singleton object, and that will do our job. 2. Copy the same object, override the copyWithZone method, and then call the class method in the method, return the singleton object. (Don’t forget to sign the NSCopying agreement before overwriting the copyWithZone method)
Some changes have also been made to the class methods
#import <Foundation/Foundation.h>
@interface Singleton : NSObject<NSCopying>+ (instancetype)sharedInstance;
@end
#import "Singleton.h"
@implementation Singleton
static Singleton *instance = nil; + (instancetype)sharedInstance{
static dispatch_once_t onceToken;
dispatch_once(&onceToken,^{
// instance = [[self alloc]init];
instance = [[super allocWithZone:NULL]init];
});
returninstance; } + (id)allocWithZone:(struct _NSZone *)zone{
return[Singleton sharedInstance]; } - (id)copyWithZone:(NSZone *)zone{
return [Singleton sharedInstance];
}
@end
Copy the code
Let’s see if the address created in different ways is the same
The statement
I am not a technical expert, just a rookie, writing this article is not to show off what, just record the problems in their work & how to solve.