John smith
John smith

Reputation: 353

Objective c circular import in Singleton class

I have two singleton classes which are defined like that

SingletonClassA.h

@interface SingletonClassA : NSObject

+ (SingletonClassA*) sharedInstance;

@end

SingletonClassA.m

#import "SingletonClassA.h"
#import "SingletonClassB.h"    

@implementation SingletonClassA

+ (SingletonClassA*) sharedInstance{
    static SingletonClassA* instance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [SingletonClassA];
        [[SingletonClassB shareInstance] methodB];
    });

    return instance;
}

@end 

SingletonClassB.h

@interface SingletonClassB : NSObject

+ (SingletonClassB*) sharedInstance;

@end

SingletonClassB.m

#import "SingletonClassB.h"
#import "SingletonClassA.h"

@implementation SingletonClassB

+ (SingletonClassB*) sharedInstance{
    static SingletonClassB* instance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [SingletonClassB];
        [[SingletonClassA shareInstance] methodA];
    });

    return instance;
}

@end 

When I build the project, everything seems to be nice but when I run on the simulator or on my phone, the application is not launching and an NSZombie error is displayed.

Class _NSZombie_BSXPCMessage is implemented in both ?? and ??.
One of the two will be used. Which one is undefined

I have tried to delete the app, clean the project and run again .. Same error. When I remove the import in one the two classes, it works fine.

Do you have an idea what did I do wrong ?

Thanks,

Upvotes: 0

Views: 124

Answers (1)

Rishab
Rishab

Reputation: 1957

Could not reproduce your problem.

SingletonClassA.h

@interface SingletonClassA : NSObject

+ (SingletonClassA *) sharedInstance;
-(void)methodA;

@end

SingletonClassA.m

#import "SingletonClassA.h"
#import "SingletonClassB.h"

@implementation SingletonClassA

+ (SingletonClassA*) sharedInstance{
    static SingletonClassA* instance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [SingletonClassA new];
        [[SingletonClassB sharedInstance] methodB];
    });

    return instance;
}

@end

SingletonClassB.h

@interface SingletonClassB : NSObject

+ (SingletonClassB *) sharedInstance;

-(void)methodB;

@end

SingletonClassB.m

#import "SingletonClassB.h"
#import "SingletonClassA.h"

@implementation SingletonClassB

+ (SingletonClassB*) sharedInstance{
    static SingletonClassB* instance = nil;

    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        instance = [SingletonClassB new];
        [[SingletonClassA sharedInstance] methodA];
    });

    return instance;
}

@end

Importing classes in .m file should not introduce import cycle. You are not using new or alloc init. Why is that?

Upvotes: 1

Related Questions