So I'm new to Obj-C (with experience in C and C++) and I've been trying stuff.
Quite simply, I want to save and load the score and level of the user as they progress.
I have 3 functions, getFilePath
, loadData
and savaData
.
My getFilePath
and loadData
seem to work fine but I'm not able to get the saveData
to work.
here is my code for it:
-(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"];
}
My NSLog
messages return the right values and the user progresses levels,but I'm not able to save them.
The issue is that the
getFilePath
method is usingNSDocumentationDirectory
rather thanNSDocumentDirectory
. Unfortunately, Xcode's auto-complete logic makes it all too easy to pick the wrong one.Two further suggestions:
You should probably be checking the result of
writeTofile
, perhaps something like:Personally, since I often use this pattern for creating a string that references the path of a file in the
NSDocumentDirectory
directory, I created a code snippet for it which eliminates the opportunity for me to mistype this. It gives me "auto complete" for several lines of code. So, suppose I have the following two lines in my code:Clearly, use whatever code you want, but the key is to use
<#filename#>
placeholder for the parameter tostringByAppendingString
. Then, as described in the Creating a Custom Code Snippet documentation (or see NSHipster's discussion on the topic), you can drag these two lines of code to the snippet library give it a good name (and just as importantly, a good shortcut, I use "documentsPath
" for my shortcut). Now, in the future, I can just start typing "documentsPath
" in my code, and I'll be prompted with these two lines of code.Since I've started using this particular code snippet, I've never made a mistake about accidentally grabbing the wrong value instead of
NSDocumentDirectory
.