【发布时间】:2014-03-22 11:51:20
【问题描述】:
所以这是我第一次尝试在 iOS 应用中保存数据。我已经从这个网站上的各种答案中拼凑出这段代码,以便为我正在制作的游戏保存高分。我创建了一个名为 saves.plist 的 plist(在我的 Supporting Files 文件夹中)并添加了一行键 @"bestScore" 并键入 Number。测试日志返回保存成功,一切正常;然而,当我去查看 plist 之后,似乎什么都没有改变(bestScore 的值为 0)。我是否保存到在我的代码中自动创建的不同 plist?如果是这种情况,那么能够在 Xcode 中创建 plist 有什么意义?就在哪里/如何创建/存储/访问 plist 而言,这里使用的最佳实践是什么?
@implementation ViewController
- (void)viewDidLoad
{
[super viewDidLoad];
self.fm = [NSFileManager defaultManager];
self.destPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];//Documents directory
self.destPath = [self.destPath stringByAppendingPathComponent:@"saves.plist"];
// If the file doesn't exist in the Documents Folder, copy it.
if (![self.fm fileExistsAtPath:self.destPath]) {
NSString *sourcePath = [[NSBundle mainBundle] pathForResource:@"saves" ofType:@"plist"];
[self.fm copyItemAtPath:sourcePath toPath:self.destPath error:nil];
}
}
- (void)saveBestScore{
NSNumber *bestScoreBox = [NSNumber numberWithUnsignedLong:self.bestScore];
NSDictionary *data = @{bestScoreBox: @"bestScore"};
BOOL successful = [data writeToFile:self.destPath atomically:YES];
successful ? NSLog(@"YES") : NSLog(@"NO");
}
【问题讨论】:
标签: ios objective-c plist