Friday, March 18, 2011

Objective C: Logged User Singleton


//loggedUserDataSIngleton.h

#import <Foundation/Foundation.h>

@interface loggedUserDataSIngleton : NSObject {
    NSString *loginName;
}
   
@property (nonatomic, retain) NSString* loginName;
   
+(loggedUserDataSIngleton*)sharedMySingleton;
-(NSString*)obtainCurrentUserLoginName;

@end


//loggedUserDataSIngleton.m

#import "loggedUserDataSIngleton.h"


@implementation loggedUserDataSIngleton

@synthesize loginName;

static loggedUserDataSIngleton *_sharedMySingleton = nil;

+(loggedUserDataSIngleton*)sharedMySingleton
{
    @synchronized([loggedUserDataSIngleton class])
    {
        if (!_sharedMySingleton) {
            [[self alloc] init];
        }
       
        return _sharedMySingleton;
    }
   
    return nil;
}

+(id)alloc
{
    @synchronized([loggedUserDataSIngleton class])
    {
        NSAssert(_sharedMySingleton == nil, @"Attempted to allocate a second instance of a singleton.");
        _sharedMySingleton = [super alloc];
        return _sharedMySingleton;
    }
   
    return nil;
}

-(id)init {
    self = [super init];
    if (self != nil) {
        // initialize stuff here
    }
    return self;
}

-(NSString*)obtainCurrentUserLoginName {
    return self.loginName;
}

@end


then, in the .m you want to use the singleton, you have to import the loggedUserDataSIngleton.h:

#import "loggedUserDataSIngleton.h" 
....
....
....
....
// store login Name in singleton class  
//[loggedUserDataSIngleton sharedMySingleton].loginName = @"John";


// get stored login name
[[loggedUserDataSIngleton sharedMySingleton] loginName]




Reference:  http://getsetgames.com/2009/08/30/the-objective-c-singleton/

No comments: