NSUserDefault issues. save/retrieve data including a UIImageView grid[][]
I'm trying to save information in a game but I got stuck.
I tried a different approach before trying with NSUserDefault.
What I'm trying to save is
*PlayerScore //NSInteger
*HighScore //NSInteger
*Level //NSInteger
*Time //int
*The button settings on SFX and background music
*The background musics position, so it will resume where it stopped
*the grid which is the gamefield and the bricks upon it (the grid is 6x6 and is also a UIImageView *grid[][] type, the bricks on it are 35)
-(void)saveGameState {
NSLog(@"saveGameState");
NSLog(@"totalrubies %d", totalrubies);
NSLog(@"playerscore %d", playerscore);
NSLog(@"highscore %d", highscore);
NSLog(@"level %d", level);
NSLog(@"totalseconds %d", totalSeconds);
[[NSUserDefaults standardUserDefaults] setInteger:totalrubies forKey:kRubiesKey];
[[NSUserDefaults standardUserDefaults] setInteger:playerscore forKey:kPScoreKey];
[[NSUserDefaults standardUserDefaults] setInteger:highscore开发者_Python百科 forKey:kHScoreKey];
[[NSUserDefaults standardUserDefaults] setInteger:level forKey:kLevelKey];
[[NSUserDefaults standardUserDefaults] setInteger:totalSeconds forKey:kTimeKey];
[[NSUserDefaults standardUserDefaults] synchronize];
for (int y = 0; y < BRICKHEIGHT; y++)
{
for (int x = 0; x < BRICKWIDTH; x++)
{
[[NSUserDefaults standardUserDefaults] setObject:grid[x][y] forKey:kGridKey];
NSLog(@"grid[BRICKWIDTH][BRICKHEIGHT] %d", grid[x][y].tag);
}
}
}
I tried this way also
NSData *ImageData = UIImagePNGRepresentation (grid[x][y]);
[NSUserDefaults standardUserDefaults] setObject:ImageData forKey:kGridKey];
but then I got an warning: incompatible Objective-C types 'struct UIImageView *', expected 'struct UIImage *' when passing argument 1 of 'UIImagePNGRepresentation' from distinct Objective-C type
I have managed, I think, to save everything except the last 3 * in the list. I need help with those specially with the grid part, that's prio 1.
You should give UIImagePNGRepresentation()
the UIImage
in the UIImageView
, hence this error message.
Try :
UIImageView *imgView = grid[x][y];
NSData *ImageData = UIImagePNGRepresentation(imgView.image);
[NSUserDefaults standardUserDefaults] setObject:ImageData forKey:kGridKey];
NSUserDefaults
is not really a great solution for this. Have you considered CoreData or the filesystem?
Saving the images themselves seems unnecessary and wasteful. All you have to do is record the state of the game - i.e. which brick is in which position. You should be able to recreate the view from that data easily.
精彩评论