在NSUserDefaults中加载数据

我已经做了编码,以保存高分在NSuserdefaults,但我不知道如何加载数据从nsuserdefaults并显示在表中。 请帮忙。

NSString *name; name = nametextbox.text; NSDictionary *player = [NSDictionary dictionaryWithObjectsAndKeys: [NSString stringWithFormat:@"%@", name], @"name",[NSString stringWithFormat:@"%d", myScore], @"score",nil]; [highScore addObject:player]; NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:@"score" ascending:NO]; [highScore sortUsingDescriptors:[NSArray arrayWithObject:sort]]; [sort release]; [[NSUserDefaults standardUserDefaults] setObject:highScore forKey:@"highScore"]; 

你应该能够按照你期望的方式加载它(比如在NSDictionary访问一个值):

 NSArray *highScore = [[NSUserDefaults standardUserDefaults] objectForKey:@"highScore"]; 

更新

要在表格视图中显示数组中的数据,您需要创build一个视图控制器并将该数组用作数据源。 最简单的方法是通过UITableViewController 。 这应该让你开始执行该控制器:

 // HighScoreViewController.h @interface HighScoreViewController : UITableViewController { NSArray *highScores; } @property (nonatomic, retain) NSArray *highScores; @end 

 // HighScoreViewController.m #import HighScoreViewController.h static const NSInteger kNameLabelTag = 1337; static const NSInteger kScoreLabelTag = 5555; @implementation HighScoreViewController @synthesize highScores; - (void)viewDidLoad { [self setHighScores:[[NSUserDefaults standardUserDefaults] objectForKey:@"highScore"]]; } - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView { return 1; } - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return [self.highScores count]; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { static NSString *cellIdentifier = @"PlayerCell"; UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier]; if (cel == nil) { cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:cellIdentifier] autorelease]; // Create UILabels for name and score and add them to your cell UILabel *nameLabel = [[UILabel new] autorelease]; [nameLabel setTag:kNameLabelTag]; [cell.contentView addSubview:nameLabel]; UILabel *scoreLabel = [[UILabel new] autorelease]; [scoreLabel setTag:kScoreLabelTag]; [cell.contentView addSubview:scoreLabel]; // Set other attributes common to all of your cells here // You will also need to set the frames of these labels (nameLabel.frame = CGRectMake(...)) } NSDictionary *player = [self.highScores objectAtIndex:indexPath.row]; NSString *name = [player objectForKey:@"name"]; NSString *score = [player objectForKey:@"score"]; [(UILabel *)[cell.contentView viewWithTag:kNameLabelTag] setText:name]; [(UILabel *)[cell.contentView viewWithTag:kScoreLabelTag] setText:score]; return cell; } @end 

使用UITableView要记住的关键是单元格被重用,所以你需要小心你初始化/configuration单元格子视图的位置。