【Objective-C】NSUserDefaultsを使ってハイスコアをセーブ
BeeClusterのメインプログラムがほぼ完成し、リリースに向け少しずつ改良しています。
今回は、NSUserDefaultsを使ってハイスコアを記録できるようにしました。
アプリケーションを削除しない限りハイスコアを保持できますので、ハイスコアを更新する楽しみをゲームに付け加えられます。
NSUserDefaultsを使えば情報を簡単に保存したり読み込んだりできます。
使う側はそれがどこにどのように記録されているのかは意識する必要はありません。
BeeClusterではスコアや自キャラの数を表示するために下記のInfoLayerというクラスを使っています。
変更した部分は2行だけです。
まず、initメソッドの冒頭で、_highScoreというインスタンス変数にhighScoreというキーで値をNSUserDefaultsから読み込みます。
NSUserDefaultsのシングルトンインスタンスであり、[NSUserDefaults standardUserDefaults]でアクセスします。整数を読むときのメソッドはintegerForKey:です。
初回起動時は記録前なので読み込むデータはありませんが、その場合は0を返してくれるので気にせずその値を使います。
一方、setScore:メソッドではNSUserDefaultsに値を記録します。setInteger:forKey:メソッドを使います。
ファイルへの書き込みなどを意識する事なくたったこれだけでハイスコアを記録できるのは便利ですね。
@implementation InfoLayer { NSInteger _score; NSInteger _highScore; NSInteger _beeCount; CCLabelTTF* _scoreLabel; CCLabelTTF* _highScoreLabel; CCLabelTTF* _beeCountLabel; } + (InfoLayer *)sharedInfo { static InfoLayer* sharedInstance = nil; if (sharedInstance == nil) { sharedInstance = [[self alloc] init]; } return sharedInstance; } - (id)init { if ((self = [super init])) { _score = 0; _highScore = [[NSUserDefaults standardUserDefaults] integerForKey:@"highScore"]; _beeCount = 0; NSString* scoreString = [NSString stringWithFormat:@"%07d", _score]; NSString* highScoreString = [NSString stringWithFormat:@"%07d", _highScore]; NSString* beecountString = [NSString stringWithFormat:@"%d", _beeCount]; _scoreLabel = [CCLabelTTF labelWithString:scoreString fontName:@"arial" fontSize:24]; _highScoreLabel = [CCLabelTTF labelWithString:highScoreString fontName:@"arial" fontSize:24]; _beeCountLabel = [CCLabelTTF labelWithString:beecountString fontName:@"arial" fontSize:24]; [self addChild:_scoreLabel]; [self addChild:_highScoreLabel]; [self addChild:_beeCountLabel]; _scoreLabel.anchorPoint = ccp(1.0, 1.0); //anchorPointは0.0〜1.0で指定!! _highScoreLabel.anchorPoint = ccp(0.0, 1.0); _beeCountLabel.anchorPoint = ccp(0.5, 1.0); CGPoint scoreOffset = ccp(-10, 0); CGPoint highScoreOffset = ccp(10, 0); CGPoint beeCountOffset = ccp(0, 0); CGSize winSize = [CCDirector sharedDirector].winSize; CGPoint topRight = ccp(winSize.width, winSize.height); CGPoint topLeft = ccp(0, winSize.height); CGPoint topCenter = ccp(winSize.width/2, winSize.height); _scoreLabel.position = ccpAdd(topRight, scoreOffset); _highScoreLabel.position = ccpAdd(topLeft, highScoreOffset); _beeCountLabel.position = ccpAdd(topCenter, beeCountOffset); } return self; } - (void)setScore:(NSInteger)score { _score = score; [_scoreLabel setString:[NSString stringWithFormat:@"%07d", _score]]; if (_score > _highScore) { _highScore = _score; [[NSUserDefaults standardUserDefaults] setInteger:_highScore forKey:@"highScore"]; [_highScoreLabel setString:[NSString stringWithFormat:@"%07d", _highScore]]; } } - (void)setBeeCount:(NSInteger)beeCount { _beeCount = beeCount; [_beeCountLabel setString:[NSString stringWithFormat:@"%d", _beeCount]]; } @end