如果您尝试为多个玩家保存游戏状态,那么您的做法可能是错误的。我不想阻碍您当前的进步,但我想指出一些改进的途径。
第一点: NSDictionary
对象(以及 plist)可以在树结构中存储数据,因此不需要为每个用户拥有一组不同的键:
NSDictionary* dict = [NSDictionary dictionaryWithObjectsAndKeys:
[NSArray arrayWithObjects:@"currentGame", @"currentGameType", ..., nil],
@"player1",
[NSArray arrayWithObjects:@"currentGame", @"currentGameType", ..., nil],
@"player2",
..., nil];
第二点:更进一步,我认为你真正想要的是另一个完整的字典对于每个玩家:
NSMutableDictionary * playerInfo;
playerInfo = [NSMutableDictionary dictionaryWithCapcity:0];
[playerInfo setObject:@"1" forKey:@"currentGame"];
[playerInfo setObject:@"2" forKey:@"currentGameType"];
[playerInfo setObject:@"what's up?" forKey:@"currentGameQuestion"];
...
NSMutableDictionary * allPlayers;
allPlayers = [NSMutableDictionary dictionaryWithCapcity:0];
NSInteger playerNum;
for (playerNum = 1; playerNum <= 6; playerNum++) {
NSString * key = [NSString stringWithFormat:@"Player%d", playerNum];
[allPlayers setObject:playerInfo forKey:key];
}
现在,保存并阅读后allPlayers
字典中,您将按如下方式访问单个记录:
NSDictionary * player2Info = [readDict objectForKey:@"player2"];
NSLog(@"%@", player2Info); // show all keys and values for player 2
NSLog(@"%@", [player2Info valueForKey:@"currentGame"]; // show a single value
第三点:如果您要存储多个用户的游戏状态,proper做到这一点的方法(从面向对象的角度来看)是创建一个Player
类,然后加载并保存该类的实例。乍一看,它看起来像这样:
@interface Player {
NSString * currentGame;
NSString * currentGameType;
NSString * currentGameQuestion;
...
}
@property (nonatomic, copy) NSString * currentGame;
@property (nonatomic, copy) NSString * currentGameType;
@property (nonatomic, copy) NSString * currentGameQuestion;
...
- (void)loadFromDictionary:(NSDictionary *)dict;
- (NSDictionary *)saveAsDictionary;
@end
@implementation Player
@synthesize currentGame;
@synthesize currentGameType;
@synthesize currentGameQuestion;
...
- (void)loadFromDictionary:(NSDictionary *)dict {
[self setCurrentGame:[dict objectForKey:@"currentGame"]];
[self setCurrentGameType:[dict objectForKey:@"currentGameType"]];
[self setCurrentGameQuestion:[dict objectForKey:@"currentGameQuestion"]];
...
}
- (NSDictionary *)saveAsDictionary {
return [NSDictionary dictionaryWithObjectsAndKeys:
currentGame, @"currentGame";
currentGameType, @"currentGameType";
currentGameQuestion, @"currentGameQuestion";
...
nil];
}
@end
现在,您可以按如下方式加载和保存玩家:
Player * player1 = [[[Player alloc] init] autorelease];
Player * player2 = [[[Player alloc] init] autorelease];
...
NSDictionary * players = [NSDictionary dictionaryWithObjectsAndKeys:
[player1 saveAsDictionary], @"Player1",
[player2 saveAsDictionary], @"Player2",
...
nil];
// save dictionary
[players writeToFile:...
// load dictionary
NSDictionary * readDict = ...
[player1 loadFromDictionary:[readDict objectForKey:@"Player1"]];
[player2 loadFromDictionary:[readDict objectForKey:@"Player2"]];
...
See also:
Objective-C 中的嵌套数组 ( NSMutableArray ) https://stackoverflow.com/q/1244833/33686(玩家对象)
存储和检索多维 NSMutableArray 的最佳方法是什么? https://stackoverflow.com/q/2136905/33686(属性列表序列化)