How properly assign singleton to a variable in iOS? - ios

I have a project written in Objective-C. Inside it I use singleton.
Its declaration is:
+ (id)sharedInstance
{
static id sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
I init it inside each class where I use it by this code:
singApp = [XXXsingApplication sharedInstance];
When I run Xcode Analyzer I get following warning:
Instance variable used while 'self' is not set to the result of
'[(super or self) init...]'
Why I get this warning?
I suppose I have some general misunderstanding of matter, because AFAIK it has only single instance and must not be init again to avoid creating several instances?
EDIT:
My init looks like:
-(id)init
{
self = [super init];
// init read-only values
_appSwVersion = APP_SOFT_VERSION;
_appSwDateTime = APP_SOFT_DATETIME;
_websDns = WEBS_DNS;
_testWebsUrl = TEST_WEBS_DNS_URL;
// init properties dictionary
_propListDict = [[NSMutableDictionary alloc] init];
#try {
if (self) {
// load settings
[self loadSettingsFromFile];
// init custom Bundle
[self setCustomBundle];
}
}
#catch (NSException *exception) {
NSLog(#"EXCEPTION\nName-> %#\nDescription-> %#", [exception name], [exception description]);
}
return self;
}

Exceptions are there to catch programming errors. You don't catch and handle exceptions in Objective-C. When an exception happens, you let it crash. This is Objective-C, not Java or C++. You don't handle exceptions, you fix the code.
You should check whether self == nil immediately after calling [super init]. Think about what you are doing: You are assigning to an instance variable which will lead to a crash if self == nil. Sure, there will be cases where people are 100% sure that self cannot be nil. But five lines later, you check whether self == nil. That combination is a clear indication of a bug. If you check, you must check before you assign to an instance variable. If you assign to an instance variable, any check is too late.

Your code should look like this.
-(id)init {
self = [super init];
#try {
if (self) {
// init read-only values
_appSwVersion = APP_SOFT_VERSION;
_appSwDateTime = APP_SOFT_DATETIME;
_websDns = WEBS_DNS;
_testWebsUrl = TEST_WEBS_DNS_URL;
// init properties dictionary
_propListDict = [[NSMutableDictionary alloc] init];
// load settings
[self loadSettingsFromFile];
// init custom Bundle
[self setCustomBundle];
}
} #catch (NSException *exception) {
NSLog(#"EXCEPTION\nName-> %#\nDescription-> %#", [exception name], [exception description]);
}
return self;
}

Related

Why my code did not get into [super init] function?

There are three class Question,Choiceand Blank,and Question is the super class of Choice and Blank.
Then, I write some methods as follows:
- (instancetype)initWithQuestionType:(NSString *)questionType
{
NSLog(#"**class:%#",[self class]);
if([self isMemberOfClass:[Question class]])
{
self = nil;
if([questionType isEqualToString:#"choice"])
{
NSLog(#"--class:%#",[self class]);
self = [[Choice alloc] initWithQuestionType:questionType];
NSLog(#"++class:%#",[self class]);
}
else
{
self = [[Blank alloc] initWithQuestionType:questionType];
}
return self;
}
return [super init];
}
- (instancetype)init
{
NSLog(#"Init!");
return [self initWithQuestionType:#"unKnow"];
}
and then:
Question *question = [[Question alloc] initWithQuestionType:#"choice"];
the output is:
2015-10-16 20:58:50.278 initSample[3687:161396] **class:Question
2015-10-16 20:58:50.279 initSample[3687:161396] --class:(null)
2015-10-16 20:58:50.279 initSample[3687:161396] **class:Choice
2015-10-16 20:58:50.280 initSample[3687:161396] ++class:Choice
and I can't understand why [super init] did not be executed?
Your [super init] method is being called:
[Question initWithQuestionType] is called.
The first if is true, so it's entered.
The question type is "choice" so [Choice initWithQuestionType:] is called.
As Choice does not override -initWithQuestionType:, this will call [Question initWithQuestionType:] again.
This time the if is false, so it's not entered, and [super init] is being called.
This is being shown in your log messages (add an another log call before the [super init] method, to prove this).
However it's a very confusing and difficult to maintain factory method, and it's much easier to use a class factory method, as below. That way your init methods will be much more straight-forward and easier to maintain.
+ (Question *)questionWithType:(NSString *)type
{
if ([type isEqualToString:#"choice"])
return [[Choice alloc] init];
else
return [[Blank alloc] init];
}
Also consider using an enum to represent the type, rather than a string (quicker/more efficient).

Singleton object or Use the class for some Build Configuration only - iOS

I have a singleton class. This class has methods which use core data and are to be used only for some build configuration.
+(AClass*) singletonInstance {
static dispatch_once_t dispatchCall;
static AClass *shared=nil;
dispatch_once(&dispatchCall, ^{
shared=[[AClass alloc] init];
});
return shared;
}
-(id)init{
self=[super init]
if(self){
[self initCoreData];
}
return self;
}
So, if I use the following code will this be a correct way to handle it. I think, this will be handled at compile time, so at run time it will be always nil, so any method called on
[[AClass singletonInstance] someMethod]
will not work , As a message passed to a nil object, which will not crash but at the same time, it will not respond to that message. Also, it would not init the core data.
Approach 1
+(AClass*) singletonInstance {
#if DEBUG==6
static dispatch_once_t dispatchCall;
static AClass *shared=nil;
dispatch_once(&dispatchCall, ^{
shared=[[AClass alloc] init];
});
return shared;
#else
return nil;
#endif
}
Approach 2
I have one more helper class which has singleton method. I have this method and is used in many other classes (So, if in future if I change it to DEBUG preprocessor value to say "10", then I will have to make change at one place only). would be ok to use it over here also?
-(BOOL)shouldInitContent{
#if DEBUG==6
return YES;
#else
return NO;
#endif
}
+(AClass*) singletonInstance {
if([[AHelperClass helperInstance] shouldInitContent]){
static dispatch_once_t dispatchCall;
static AClass *shared=nil;
dispatch_once(&dispatchCall, ^{
shared=[[AClass alloc] init];
});
return shared;
}else{
return nil;
}
}
Which of the above two approaches could be efficient?
I would go with approach #1, because it will help you minimize the memory consumption.
In the second approach you are using two singleton instance which I doesn't recommend.

Singleton with parameter iOS

I need to implement a singleton class that takes in a parameter. The same object will be passed as a parameter every single time so the resultant singleton object will always be the same.
I am doing something like the code below. Does this look ok? Is there a better way of achieving what I want to achieve?
- (id)sharedInstanceWithAccount:(UserAccount *)userAccount {
if (!sharedInstance) {
#synchronized(self) {
sharedInstance = [[[self class] alloc] initWithAccount:userAccount];
}
}
return sharedInstance;
}
- (id)initWithAccount:(UserAccount *)userAccount {
self = [super init];
if (self) {
_userAccount = userAccount;
}
return self;
}
- (id)init {
NSAssert(false,
#"You cannot init this class directly. It needs UserAccountDataSource as a paramter");
return nil;
}
+ (id)alloc {
#synchronized(self) {
NSAssert(sharedInstance == nil, #"Attempted to allocated a second instance of the singleton");
sharedInstance = [super alloc];
return sharedInstance;
}
return nil;
}
There are a number of problem in this design:
As recommended by Apple, should dispatch_once instead of #synchronized(self) for singleton:
static MyClass *sharedInstance = nil;
static dispatch_once_t onceToken = 0;
dispatch_once(&onceToken, ^{
sharedInstance = [[MyClass alloc] init];
// Do any other initialisation stuff here
});
return sharedInstance;
Refer to this question for more detail: Why does Apple recommend to use dispatch_once for implementing the singleton pattern under ARC?
Bad API design to put singleton in alloc.
As indicated by the name of the method alloc, it means that some memory will be allocated. However, in your case, it is not. This attempt to overwrite the alloc will cause confusion to other programmers in your team.
Bad idea to use NSAssert in your -init.
If you want to disable a method, disable it by putting this in your header file:
- (id)init __attribute__((unavailable));
In this case, you will get a compile error instead of crashing the app at run time.
Refer to this post for more detail: Approach to overriding a Core Data property: isDeleted
Moreover, you can even add unavailable message:
- (id)init __attribute__((unavailable("You cannot init this class directly. It needs UserAccountDataSource as a parameter")));
Sometime input parameters is ignored with no warning.
In your following code, how would the programmer who is calling this function know that the input parameter userAccount is sometimes ignored if an instance of the class is already created by someone else?
- (id)sharedInstanceWithAccount:(UserAccount *)userAccount {
if (!sharedInstance) {
#synchronized(self) {
sharedInstance = [[[self class] alloc] initWithAccount:userAccount];
}
}
return sharedInstance;
}
In short, don't think it is a good idea to create singleton with parameter. Use conventional singleton design is much cleaner.
objA = [Object sharedInstanceWithAccount:A];
objB = [Object sharedInstanceWithAccount:B];
B is ignored.
userAccount in objB is A.
if userAccount B in objB, you will change sharedInstanceWithAccount.
- (id)sharedInstanceWithAccount:(UserAccount *)userAccount {
static NSMutableDictionary *instanceByAccount = [[NSMutableDictionary alloc] init];
id instance = instanceByAccount[userAccount];
if (!instance) {
#synchronized(self) {
instance = [[[self class] alloc] initWithAccount:userAccount];
instanceByAccount[userAccount] = instance;
}
}
return instance;
}

Thread Safe Singleton in iOS6

Im trying to get an updated version of the Singleton Design Pattern which is thread safe. Here is one version that I know. However, I cannot make it work in iOS6
Here is what Im trying to do:
Here is my Class method
+(id)getSingleton
{
static dispatch_once_t pred;
static EntryContainerSingleton *entriesSingleton = nil;
dispatch_once(&pred, ^{
entriesSingleton = [[super alloc] init];
});
return entriesSingleton;
}
+(id)alloc
{
#synchronized([EntryContainerSingleton class])
{
NSLog(#"inside alloc of EntryContainerSingleton");
ERROR >>>>> NSAssert(entriesSingleton == nil, #"Attempted to allocate a second instance of a singleton.");
ERROR >>>>> entriesSingleton = [super alloc];
ERROR >>>>> return entriesSingleton;
}
return nil;
}
-(id)init
{
self = [super init];
......Some custom INitialization
return self;
}
This code throws an error as marked above. The error message says Use of undeclared identifier. In addition the link above recommends the use of
[[allocWithZone:nil] init]
When I use it like this it complains
+(id)allocWithZone:(NSZone*)zone
{
return [self instance];
}
After hours of trying to make it work. It would be great if someone could point out how to do this right. Ive spent much time googling and haven't found a complete implementation example.
Thanks
Why not just use +initialize?
static MyClass *gSingleton;
+(void) initialize {
if ( self == [MyClass class] ) {
gSingleton = [MyClass new];
}
}
+(MyClass*) getSingleton {
return gSingleton;
}
It's thread-safe. The only issue is that it doesn't prevent someone from allocating a second object by using alloc/init or new.

ARC error: init methods must return a type related to the receiver type [4]

Whats wrong with this code under ARC? I get above error:
- (Moment *)initMoment:(BOOL)insert {
if (insert) {
self.moment = [NSEntityDescription insertNewObjectForEntityForName:#"Moment" inManagedObjectContext:self.managedObjectContext];
} else {
self.moment = [NSEntityDescription insertNewObjectForEntityForName:#"Moment" inManagedObjectContext:nil];
}
return self.moment;
}
The init method that was posted in the question was in the wrong form. The init method should (usually) have the form:
-(id)initWithParams:(BOOL)aBoolParam {
if (self = [super init]) {
//do stuff
}
return self;
}
The problem with code above was that it was done as a class method, so if the poster wanted to do this he had to do moment = [[Moment alloc] init] and return it.

Resources