Simply declare your class in your header file like so:

@interface MyClass : NSObject

+ (RecordingsMgr*)instance;

@end

Then in your .m file, declare the instance function like so:

@implementation MyClass

+ (MyClass*)instance {
    static MyClass* _myClassInstance = nil;
    if (!_myClassInstance) {
        _myClassInstance = [[MyClass alloc] init];
    }
    return _myClassInstance;
}

@end

Then, whenever you need the instance somewhere, get it like so:

[[MyClass instance] someInstanceMethod]

Beautifully simple, and no mucking around with app delegates, it’ll simply get created whenever first needed. Not thread safe, however, so stick to the main thread.

Update

If you’re concerned about thread safety, you can use this technique:

http://cocoasamurai.blogspot.com/2011/04/singletons-your-doing-them-wrong.html

Thanks for reading! And if you want to get in touch, I'd love to hear from you: chris.hulbert at gmail.

Chris Hulbert

(Comp Sci, Hons - UTS)

iOS Developer (Freelancer / Contractor) in Australia.

I have worked at places such as Google, Cochlear, Assembly Payments, News Corp, Fox Sports, NineMSN, FetchTV, Coles, Woolworths, Trust Bank, and Westpac, among others. If you're looking for help developing an iOS app, drop me a line!

Get in touch:
[email protected]
github.com/chrishulbert
linkedin
my resume



 Subscribe via RSS