Reputation: 27517
I am trying to make a small game where users answer questions. The overall flow will go like this:
My problem is I don't really need to store user info (name, answers, etc) in a database since that data is useless after the round is over. However, I need it to persist enough so that I can access that data across the view controllers before the round is over.
For the difficulty level I'm using a custom property on AppDelegate to persist the setting:
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);
}
However, this doesn't feel very scalable since I am going to have many other properties and I don't feel like that's what AppDelegate is meant to be used for.
Is there a common way to persist data for this sort of thing?
Upvotes: 1
Views: 85
Reputation: 2349
I think you need to have a kind of game manager. A manager is commonly used as a singleton that means you will have only one instance of this class. It could be something like:
-header file:
@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
And so you will update your code like that:
- (IBAction)setDifficultyLevel:(id)sender {
UIButton *button = (UIButton *)sender;
NSString *difficulty = [[button titleLabel] text];
GameManager *gameManager = [GameManager sharedInstance];
gameManager.difficultyLevel = difficulty;
}
You can also have a weak property on your manager in each view controller if you prefer.
Upvotes: 1