Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 6177315
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: May 24, 20262026-05-24T00:15:06+00:00 2026-05-24T00:15:06+00:00

I am trying to create a singleton User class in my app, here’s the

  • 0

I am trying to create a singleton User class in my app, here’s the code:

#import "User.h"
#import "Login.h"
#import "SFHFKeychainUtils.h"

// Constants
static NSString* const kDBUserCurrentUserIDDefaultsKey = @"kDBUserCurrentUserIDDefaultsKey";

// Current User singleton
static User* currentUser = nil;

@implementation User
@synthesize username = _username;
@synthesize password = _password;
@synthesize delegate = _delegate;


- (id)init
{
    self = [super init];
    if (self) {
        // Initialization code here.
    }
    return self;
}

+ (NSString*)primaryKeyProperty {
    return @"username";
}

+ (User*)currentUser {
    if (nil == currentUser) {

        id username = [[NSUserDefaults standardUserDefaults] objectForKey:@"kApplicationUserNameKey"];
        if (!username) {
            currentUser = [self new];
        } else{
             NSLog(@"CURRENT USER");
            return self;
        }

        [currentUser retain];
    }

    return currentUser;
}

+ (void)setCurrentUser:(User*)user {
    [user retain];
    [currentUser release];
    currentUser = user;
}

/**
 * Implementation of a RESTful login pattern. We construct an object loader addressed to
 * the /login resource path and POST the credentials. The target of the object loader is
 * set so that the login response gets mapped back into this object, populating the
 * properties according to the mappings declared in elementToPropertyMappings.
 */
- (void)loginWithUsername:(NSString*)username andPassword:(NSString*)password delegate:(NSObject<DBUserAuthenticationDelegate>*)delegate {
    _delegate = delegate;

    //[RKObjectManager sharedManager].client.username = username;
    //[RKObjectManager sharedManager].client.password = password;

    self.username = username;
    self.password = password;

    RKObjectMapping * userMapping = [[RKObjectManager sharedManager].mappingProvider objectMappingForKeyPath:@"LoginViewController"];
    [[RKObjectManager sharedManager] loadObjectsAtResourcePath:@"/account/verify.json" objectMapping:userMapping delegate:self];
}

/**
* Implementation of a RESTful logout pattern. We POST an object loader to
* the /logout resource path. This destroys the remote session
*/
- (void)logout/*:(NSObject<DBUserAuthenticationDelegate>*)delegate */{  
    NSError * error = nil;
    [[NSUserDefaults standardUserDefaults] setValue:nil forKey:@"kApplicationUserNameKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [SFHFKeychainUtils deleteItemForUsername:self.username andServiceName:@"convore" error:&error];

    NSLog(@"LOGGING OUT");
    if ([self.delegate respondsToSelector:@selector(userDidLogout:)]) {
        [self.delegate userDidLogout:self];
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:@"DBUserDidLogoutNotification" object:nil];
}

- (void)loginWasSuccessful {
    // Upon login, we become the current user
    [User setCurrentUser:self];
    NSError * error = nil;

    // Persist the username for recovery later
    [[NSUserDefaults standardUserDefaults] setValue:self.username forKey:@"kApplicationUserNameKey"];
    [[NSUserDefaults standardUserDefaults] synchronize];
    [SFHFKeychainUtils storeUsername:self.username andPassword:self.password forServiceName:@"convore" updateExisting:TRUE error:&error];

    // Inform the delegate
    if ([self.delegate respondsToSelector:@selector(userDidLogin:)]) {
        [self.delegate userDidLogin:self];
    }

    [[NSNotificationCenter defaultCenter] postNotificationName:@"DBUserDidLoginNotification" object:self];
}

- (void)request:(RKRequest*)request didLoadResponse:(RKResponse*)response 
{
    NSLog(@"Loaded payload: %@", [response bodyAsString]);
}

- (void)objectLoader:(RKObjectLoader*)objectLoader didLoadObject:(id)object
{
    if ([objectLoader wasSentToResourcePath:@"/account/verify.json"]) {
        Login * login = (Login *) object;
        if ([login.username length] > 0)
            [self loginWasSuccessful];
    }
}


- (void)objectLoader:(RKObjectLoader *)objectLoader didFailWithError:(NSError*)error {  
    if ([objectLoader wasSentToResourcePath:@"/account/verify.json"]) {
         NSLog(@"Encountered an error: %@", error); 
        // Login failed
        if ([self.delegate respondsToSelector:@selector(user:didFailLoginWithError:)]) {
            [self.delegate user:self didFailLoginWithError:error];
        }
    } 
}

- (BOOL)isLoggedIn {
    return self.username != nil;
    //return self.singleAccessToken != nil;
}

- (void)dealloc {
    _delegate = nil;
    [_password release];
    [_passwordConfirmation release];
    [super dealloc];
}

@end

The issue is that whenever I tried to access currentUser it always breaks down. I first called the loginWithUsernameandPassword and then tried calling the currentUser, but when I call the currentUser on logout, it gives me an error:

calling this:

if ([[User currentUser] isLoggedIn])

gives me:

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '+[User isLoggedIn]: unrecognized selector sent to class 0x1a671c'

seems that currentUser is nil, why is this?

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-05-24T00:15:07+00:00Added an answer on May 24, 2026 at 12:15 am

    Quick Singleton 101 (I wish I had this when I started, lol. Everyone just pointed me to the docs which didn’t help much). The name of the singleton is going to be “Singleton”

    //Singleton.h
    #import <Foundation/Foundation.h>
    
    @interface SingletonManager : NSObject
    {
        NSDictionary* randomDictionary; //just using a dictionary for demonstrative purposes. You can make this a string or whatever you want.
    }
    
    + (Singleton*)sharedSingleton;
    
    @property (nonatomic, retain) NSDictionary *randomDictionary;
    
    @end
    

    And now the .m

    //Singleton.m
    #import "Singleton.h"
    
    static Singleton *sharedSingleton = nil;
    
    @implementation Singleton
    
    @synthesize randomDictionary;
    
    #pragma mark Singleton Method
    + (Singleton*)sharedSingleton
    {
        @synchronized(self)
        {
            if(sharedSingleton == nil)
            {
                sharedSingleton = [[super allocWithZone:NULL] init];
            }
        }
        return sharedSingleton;
    }
    @end
    

    And to set/get, first import the singleton in whatever class you need: #import "Singleton.h", then grab the singleton with Singleton *singletonManager = [Singleton sharedSingleton]; and then you can do whatever you need to as necessary. i.e. to get the description of the NSDictionary you would call [[singletonManager randomDictionary] description];

    Now this is using ARC, so if you are not you’d just have to make sure you manage your memory correctly. Enjoy.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Ok so I am trying create a login script, here I am using PHP5
I'm trying to create a simple to use singleton class to connect to mysql
I'm trying to create a global (singleton) class that can associate any type of
Trying to create a user account in a test. But getting a Object reference
Trying to create my first iPhone app that would play back audio. When I
I'm trying to achieve the following goal: Using this general singleton class: abstract class
When working with legacy code, and trying to create tests, I often break out
I'm trying to inject some Scala code into my existing Java app. (So, being
I'm trying to create a Singleton object that deals with servicing an event listener:
I'm trying to write a singleton class for maintain game data, It's called GameManager,

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.