Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a singleton for my Core Data default stack in Swift

I am trying to use a singleton for Core Data. Previously, I've been successfully able to do it by creating a class CoreDataStack.h/.m, calling the default stack method below, and its respective managed object context, in Objective-C, and works very well:

//RETURNS CoreDataStack
+ (instancetype)defaultStack {
    static CoreDataStack *defaultStack;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        defaultStack = [[self alloc]init];
    });
    
    return defaultStack;
}

However, I am using a Swift project, and I've been struggling to convert this into the latest Swift syntax. How would I go about creating this? This is my attempt so far:

class func defaultStack() -> Self {
    var defaultStack: CoreDataStack
    var onceToken: dispatch_once_t = 0
    dispatch_once(&onceToken) {
       defaultStack = self.init()
    }
    return defaultStack
}

and my Xcode generated error:

enter image description here

like image 477
Josh O'Connor Avatar asked Apr 14 '26 04:04

Josh O'Connor


1 Answers

To create a singleton, use Krakendev's single-line singleton code:

class CoreDataStack {

    // Here you declare all your properties

    static let sharedInstance = User()

    private init() {
        // If you have something to do at the initialization stage
        // you can add it here. It will only be called once. Guaranteed.
    }

    // Add the rest of your methods here

}

You will call your methods and properties as CoreDataStack.sharedInstance().property and CoreDataStack.sharedInstance().method(). I recommend using something shorter instead of sharedInstance, like service.

This solution applies in general, not only in your Core Data case.

like image 127
catalandres Avatar answered Apr 15 '26 21:04

catalandres



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!