我正在努力制作一款用户回答问题的小游戏。整体流程将如下:
我的问题是我真的不需要在数据库中存储用户信息(名称,答案等),因为该数据在一轮结束后无用。但是,我需要它足够持久化,以便我可以在轮次结束之前通过视图控制器访问该数据。
对于难度级别,我在AppDelegate上使用自定义属性来保留设置:
AppDelegate.h
@interface AppDelegate : UIResponder <UIApplicationDelegate>
@property (strong, nonatomic) UIWindow *window;
@property (strong, nonatomic) NSString *difficultyLevel;
@end
DifficultyViewController.m
- (IBAction)setDifficultyLevel:(id)sender {
UIButton *button = (UIButton *)sender;
NSString *difficulty = [[button titleLabel] text];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
appDelegate.difficultyLevel = difficulty;
}
PlayerProfileViewController.m
- (void)viewDidLoad {
[super viewDidLoad];
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
NSLog(@"Edmund: %@", appDelegate.difficultyLevel);
}
然而,由于我将拥有许多其他属性,因此我感觉不具备可扩展性,而且我并不觉得AppDelegate的用途是什么。
是否有一种常见的方法来保存此类数据?
答案 0 :(得分:1)
我认为你需要有一种游戏经理。管理器通常用作单例,这意味着您只有一个此类的实例。它可能是这样的:
- 头文件:
@interface GameManager : NSObject
@property (nonatomic, strong) NSString *difficultyLevel;
@property (nonatomic, strong) NSString *player1Name;
@property (nonatomic, strong) NSString *player2Name;
@end
-source file:
@implementation GameManager
@synthesize difficultyLevel, player1Name, player2Name;
+ (id)sharedManager {
static GameManager *sharedInstance = nil;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
sharedInstance = [[self alloc] init];
});
return sharedInstance;
}
- (id)init {
if (self = [super init]) {
// add what you need here
}
return self;
}
@end
因此您将更新代码:
- (IBAction)setDifficultyLevel:(id)sender {
UIButton *button = (UIButton *)sender;
NSString *difficulty = [[button titleLabel] text];
GameManager *gameManager = [GameManager sharedInstance];
gameManager.difficultyLevel = difficulty;
}
如果您愿意,也可以在每个视图控制器中为您的经理设置弱属性。