在NSUserDefaults中加载数据

时间:2010-12-02 07:12:27

标签: cocoa-touch ios 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"];

1 个答案:

答案 0 :(得分:1)

您应该能够按照预期的方式加载它(例如访问NSDictionary中的值):

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

<强>更新

要在表视图中显示此数组中的数据,您需要创建一个视图控制器并将该数组用作数据源。最简单的方法是通过继承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要记住的关键是细胞会被重复使用,因此您需要注意初始化/配置细胞的子视图的位置。