无法为Singleton中的BOOL字段赋值

时间:2011-08-13 16:19:48

标签: iphone ios singleton uiapplicationdelegate

我有这个单身人士:

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
应用代理

- (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;
}

到这里它就像一个魅力。问题是在LoginViewController中我改变了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.");
}

调试控制台告诉我“你还没有登录”。为什么这个?怎么了?

1 个答案:

答案 0 :(得分:2)

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

您还需要为单身人士的单个元素分配内存。