Does anyone have/know about a "local high scores" function for the iPhone? I know about the various global high score frameworks, but I want something more personal and modest--just for the user/users of the iPhone.
I'm thinking something like:
-(UIView*)highScoresForLevel:(unsigned)levelNumber user:(NSString*)userName: score:(unsigned)newScore;
you feed in the current level, user name, and score. It looks up the top 10 in NSUserDefaults
(or similar), updates with userName,newScore
if necessary, then returns a UIView
displaying the scores.
I ask because I figure this must have been done before a couple of million times.
I'm aware of the similar (but less speci开发者_如何转开发fic) SO questions such as: 1, 2 --which were not useful.
Create your custom class with the following class for encoding.
@interface HighScoreClass : NSObject
{
NSString * userName;
NSInteger score;
}
@property (nonatomic,retain) NSString * userName;
@property (nonatomic,assign) NSInteger score;
@end
@implementation HighScoreClass
@synthesize userName;
@synthesize score;
//To encode custom object
- (void)encodeWithCoder:(NSCoder *)coder
{
[coder encodeObject:userName forKey:@"userName"];
[coder encodeInteger:score forKey:@"score"];
}
//to decode your custom object
- (id) initWithCoder: (NSCoder *)coder
{
if (self = [super init])
{
self.userName = [coder decodeObjectForKey:@"userName"];
self.score = [coder decodeIntegerForKey:@"score"];
}
return self;
}
-(void)dealloc
{
[super dealloc];
[userName release];
}
@end
//To store in NSUserDefaults an array "objectArray" of HighScoreClass objects
[[NSUserDefaults standardUserDefaults] setObject:[NSKeyedArchiver archivedDataWithRootObject:objectArray] forKey:[NSString stringWithFormat@"highScoresForLevel%i",level];
//To retrieve from NSUserDefaults
NSUserDefaults *currentDefaults = [NSUserDefaults standardUserDefaults];
NSData *highScoreArraySavedArray = [currentDefaults objectForKey:[NSString stringWithFormat@"highScoresForLevel%i",level]];
if (highScoreArraySavedArray != nil)
{
NSArray *oldSavedArray = [NSKeyedUnarchiver unarchiveObjectWithData:highScoreArraySavedArray];
if (oldSavedArray != nil)
objectArray = [[NSMutableArray alloc] initWithArray:oldSavedArray];
else
objectArray = [[NSMutableArray alloc] init];
}
Then you just need to traverse the retrieved array and sort according to your requirement and display.
Hope this helps.
精彩评论