Search code examples
iphoneiossingletonuiapplicationdelegate

Can't assign value to a BOOL field in a Singleton


I have this singleton:

UserData.h

@interface UserData : NSObject {
    User *user;
}

+ (UserData *)sharedUserData;

@property (nonatomic, retain) User *user;

UserData.m

@implementation UserData

@synthesize user;

SYNTHESIZE_SINGLETON_FOR_CLASS(UserData);

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

- (void) dealloc
{
    [user release];
    [super dealloc];
}

@end

User.h

@interface User : NSObject
{
    int user_id;
    NSString *username;
    BOOL logged_in;
}

@property (nonatomic, assign) int user_id;
@property (nonatomic, retain) NSString *username;
@property (nonatomic, assign, getter=isLogged) BOOL logged_in;

@end

User.m

@implementation User

@synthesize user_id, username, logged_in;

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

    return self;
}

@end

in the app delegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
{
    self.window.rootViewController = self.tabBarController;

    BOOL logged_in = FALSE; // hardcoded for testing  

    UserData *userData = [UserData sharedUserData];
    [[userData user] setLogged_in:logged_in];

    if (!logged_in) {
        [self hideTabBar:self.tabBarController];
    }

    [self.window makeKeyAndVisible];
    return YES;
}

Up to here it works like a charm. The problem is when in the LoginViewController I change the value of logged_in:

BOOL logged_in = TRUE;    

UserData *userData = [UserData sharedUserData];
[[userData user] setLogged_in:logged_in];

if (userData.user.isLogged) {
    NSLog(@"You're logged in.");
} else {
    NSLog(@"You're not logged in.");
}

The debug console says me "You're not logged in". Why this? What's wrong?


Solution

  • - (id) init
    {
        self = [super init];
        if (self != nil) {
          self.user = [[User alloc] init];
        }
        return self;
    }
    

    You also need to allocate memory for individual element of your singleton.