只要我在 ViewControllerA ,这样就可以了:
[User sharedUser].email = @"mail@mail.com";
NSLog(@"%@ %@", [User sharedUser].email, [User sharedUser]); // mail@mail.com <User: 0x8d83220>
但如果我在 ViewControllerB 后切换,则电子邮件为空
NSLog(@"%@ %@", [User sharedUser].email, [User sharedUser]); // null <User: 0x8d83220>
为什么会出现这样的错误?
User.m
@implementation User
+ (instancetype)sharedUser
{
static User *sharedUser = nil;
if (!sharedUser) {
sharedUser = [[self alloc] init];
}
return sharedUser;
}
@end
User.h
@interface User : NSObject
@property (nonatomic, weak) NSString *email;
@end