December 11, 2013 - No Comments!

Write Obj-C Singleton Shared Instance Method Calls Quicker

A neat little trick I've just been shown when implementing a singleton within Obj-c/ Xcode. We can forget about the sharedInstance method and simply call the singleton by [UsersSettingsInstance method:parameters].

.h Header File

#import <Foundation/Foundation.h>

#define UsersSettingsInstance ((UsersSettingsModel *)[UsersSettingsModel sharedInstance])

@protocol UsersSettingsModelDelegate
@end

@interface UsersSettingsModel : NSObject
{
id delegate;
}

@property id delegate;
+ (UsersSettingsModel *)sharedInstance;

@end

.m Implementation File

#import "UsersSettingsModel.h"

@implementation UsersSettingsModel

static UsersSettingsModel * _sharedInstance = nil;

+ (UsersSettingsModel*)sharedInstance
{
static dispatch_once_t once;

dispatch_once(&once, ^ {
_sharedInstance = [[UsersSettingsModel alloc] init];
});

return _sharedInstance;
}

@end

Published by: nick in Code Sample, IOS/ XCode, Objective-C

Leave a Reply