Nir*_* G. 0 objective-c plist nsnumber ios
所以我是Obj-C的新手(具有C和C++经验),我一直在努力.
很简单,我想保存并加载用户进度时的分数和级别.
我有3个功能getFilePath,loadData和savaData.
我getFilePath和loadData似乎工作正常,但我不能获得saveData工作.
这是我的代码:
-(void)saveData
{
NSNumber *updatedScore = [NSNumber numberWithInt:score];
NSNumber *updatedLevel = [NSNumber numberWithInt:level];
NSLog(@"The level im saving is %@",updatedLevel);
NSLog(@"The score im saving is %@",updatedScore);
NSMutableArray *value = [[NSMutableArray alloc]initWithObjects:updatedLevel,updatedScore, nil];
[value writeToFile:[self getFilePath] atomically:YES];
}
-(NSString *)getFilePath
{
NSArray *pathArray = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSLog(@"the path is %@",pathArray);
return [[pathArray objectAtIndex:0]stringByAppendingPathComponent:@"saved.plist"];
}
Run Code Online (Sandbox Code Playgroud)
我的NSLog消息返回正确的值,用户进展级别,但我无法保存它们.
问题是该getFilePath方法是使用NSDocumentationDirectory而不是NSDocumentDirectory.不幸的是,Xcode的自动完成逻辑使得选择错误的逻辑非常容易.
另外两个建议:
您应该检查结果writeTofile,可能是这样的:
NSArray *array1 = @[@1, @5, @3.423];
BOOL success = [array1 writeToFile:path atomically:YES];
NSAssert(success, @"%s: write failed", __FUNCTION__);
Run Code Online (Sandbox Code Playgroud)就个人而言,由于我经常使用这种模式来创建一个引用NSDocumentDirectory目录中文件路径的字符串,因此我为它创建了一个代码片段,这使我无法输入错误的机会.它为我提供了几行代码的"自动完成"功能.所以,假设我的代码中有以下两行:
NSString *documentsPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)[0];
NSString *path = [documentsPath stringByAppendingString:<#filename#>];
Run Code Online (Sandbox Code Playgroud)
显然,使用你想要的任何代码,但关键是使用<#filename#>占位符作为参数stringByAppendingString.然后,如创建自定义代码片段文档(或参见NSHipster 关于该主题的讨论)中所述,您可以将这两行代码拖到片段库中,为它提供一个好名字(同样重要的是,一个好的快捷方式,我使用" documentsPath"作为我的快捷方式).现在,在将来,我可以documentsPath在我的代码中输入" ",然后我将会提示这两行代码.
自从我开始使用这个特定的代码片段以来,我从来没有错误地意外地抓取错误的值而不是NSDocumentDirectory.
| 归档时间: |
|
| 查看次数: |
604 次 |
| 最近记录: |