【问题标题】:iOS: How to temporarily persist data without database?iOS:如何在没有数据库的情况下临时持久化数据?
【发布时间】:2015-08-14 14:25:16
【问题描述】:

我正在尝试制作一个用户回答问题的小游戏。整体流程是这样的:

  1. 通过单击按钮选择难度级别(push segue)
  2. 玩家 1 输入名称,按“下一步”(push segue)
  3. 回答问题
  4. 回答问题
  5. 完成。
  6. 玩家 2 输入名称,按“下一步”(push segue)
  7. 回答问题
  8. 回答问题
  9. 完成。
  10. 看看大家的回答
  11. 被送回#1

我的问题是我真的不需要将用户信息(姓名、答案等)存储在数据库中,因为这些数据在回合结束后就没用了。但是,我需要它足够持久,以便我可以在回合结束之前跨视图控制器访问该数据。

对于难度级别,我使用 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 的用途是什么。

有没有一种通用的方法来为这类事情持久化数据?

【问题讨论】:

  • 为什么不创建一个单例类“SharedData”并将所有数据存储在那里?

标签: ios objective-c


【解决方案1】:

我认为你需要一个游戏经理。管理器通常用作单例,这意味着您将只有一个此类的实例。可能是这样的:

-头文件:

@interface GameManager : NSObject
@property (nonatomic, strong) NSString *difficultyLevel;
@property (nonatomic, strong) NSString *player1Name;
@property (nonatomic, strong) NSString *player2Name;
@end

-源文件:

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

如果您愿意,您还可以在每个视图控制器中为您的管理器设置一个弱属性。

【讨论】:

  • 谢谢!调度的东西到底是做什么的?那是来自C吗?它看起来不像客观 c
  • 这是为了避免多个线程在“同一”时间创建一个单例实例。更多信息:mikeash.com/pyblog/…
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-01-12
  • 1970-01-01
  • 2011-08-31
  • 2011-03-20
相关资源
最近更新 更多