我正在编写一款iPhone游戏,并且我的硬件编码水平数据运行良好,但我希望将水平数据存储在plist中并在启动时加载它。我从来没有使用过plists,也很难理解如何根据我的数据模型设置plist。
以下是我现在硬编码的方法:
(在我的appDelegate中)
- (void)loadLevels {
//setup NSNumber objects to load into sequences
NSNumber * rID = [[[NSNumber alloc] initWithInt:0] autorelease];
NSNumber * bID = [[[NSNumber alloc] initWithInt:1] autorelease];
NSNumber * gID = [[[NSNumber alloc] initWithInt:2] autorelease];
NSNumber * yID = [[[NSNumber alloc] initWithInt:3] autorelease];
NSNumber * rbID = [[[NSNumber alloc] initWithInt:4] autorelease];
NSNumber * rgID = [[[NSNumber alloc] initWithInt:5] autorelease];
NSNumber * ryID = [[[NSNumber alloc] initWithInt:6] autorelease];
NSNumber * bgID = [[[NSNumber alloc] initWithInt:7] autorelease];
NSNumber * byID = [[[NSNumber alloc] initWithInt:8] autorelease];
NSNumber * gyID = [[[NSNumber alloc] initWithInt:9] autorelease];
//Level One's Sequence
NSMutableArray * aSequence = [[[NSMutableArray alloc] initWithCapacity:1] autorelease];
[aSequence addObject: rID];
[aSequence addObject: bID];
[aSequence addObject: gID];
[aSequence addObject: yID];
[aSequence addObject: rbID];
[aSequence addObject: rgID];
[aSequence addObject: ryID];
[aSequence addObject: bgID];
[aSequence addObject: byID];
[aSequence addObject: gyID];
// Load level One
_levels = [[[NSMutableArray alloc] init] autorelease];
Level *level1 = [[[Level alloc] initWithLevelNum:1 levelSpeed:1.0 levelSequence:aSequence] autorelease];
[_levels addObject:level1];
//do the same thing for subsequent levels//
}
(这就是我实施Level Level的方法)
#import "Level.h"
@implementation Level
@synthesize levelNum = _levelNum;
@synthesize levelSpeed = _levelSpeed;
@synthesize levelSequence = _levelSequence;
- (id)initWithLevelNum:(int)levelNum levelSpeed:(float)levelSpeed levelSequence:(NSMutableArray *)levelSequence {
if ((self = [super init])) {
self.levelNum = levelNum;
self.levelSpeed = levelSpeed;
self.levelSequence = [[[NSMutableArray alloc] initWithArray:levelSequence] autorelease];
}
return self;
}
- (void)dealloc {
[_levelSequence release];
_levelSequence = nil;
[super dealloc];
}
@end
我只是没有得到如何设置一个plist来存储我的数据以匹配我的模型。有人可以给我一些建议吗?
此外: (这是我认为我需要设置plist的方式 - 数据模型只是初始化我的级别的三个变量(上图)。如果你查看我当前的plist,可能会更清楚它是如何设置的,但是每个级别都包含在内of:级别编号,级别速度和表示该级别所需序列的数字数组。)
现在,如果我确实有正确的设置,我如何将值加载到我的程序中?
答案 0 :(得分:11)
将plist文件添加为项目中的资源文件。比如,它的名字是config.plist
获取资源文件的路径。 (但是,请注意[NSBundle mainBundle],因为它不会在单元测试中返回单元测试包。)
NSString *plistPath = [[NSBundle mainBundle] pathForResource:@"config" ofType:@"plist"];
// this is autoreleased. you can retain it if needed NSArray *levelArray = [NSArray arrayWithContentsOfFile:plistPath];
NSDictionary *level = [levelArray objectAtIndex:i];
NSArray *seq = [level objectForKey:@"levelSequence"];
希望它有所帮助。请注意,我没有编译代码,因此可能存在一些拼写错误。
答案 1 :(得分:1)
您应该做的是创建一个NSDictionary
,其中包含您想要的所有适用数据,然后将其读取并写入NSUserDefaults
。