gpt4 book ai didi

iphone - 无法为单例中的 BOOL 字段赋值

转载 作者:行者123 更新时间:2023-11-29 11:21:12 24 4
gpt4 key购买 nike

我有这个单例:

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

用户.m

@implementation User

@synthesize user_id, username, logged_in;

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

return self;
}

@end

在应用委托(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;
}

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

调试控制台告诉我“您尚未登录”。为什么这个?怎么了?

最佳答案

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

您还需要为单例的单个元素分配内存。

关于iphone - 无法为单例中的 BOOL 字段赋值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7051709/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com