有时候,特别是如果我玩过设置或者应用程序已经强行退出所有格式都搞砸了,因为这些值会返回null。
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"Cell";
bool bold = [[NSUserDefaults standardUserDefaults] boolForKey:@"bold"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
cell.textLabel.lineBreakMode = UILineBreakModeWordWrap;
cell.textLabel.numberOfLines = 0;
}
int fontSize = [[NSUserDefaults standardUserDefaults] integerForKey:@"fontSize"];
NSString *fontFace = bold? @"Helvetica":[[NSUserDefaults standardUserDefaults] stringForKey:@"fontFace"];
cell.textLabel.font = [UIFont fontWithName:fontFace size:(float)fontSize];
NSString *cellText = romanized? @"Romanized":@"Text";
cell.textLabel.text = [[self.myDataArray objectAtIndex:indexPath.row] objectForKey:cellText];
return cell;
}
使用InAppSettingsKit中的代码进行编辑,在我的rootview控制器中执行此操作:
- (void)settingsViewControllerDidEnd:(IASKAppSettingsViewController*)sender {
[[NSUserDefaults standardUserDefaults] synchronize];
[self dismissModalViewControllerAnimated:YES];
// your code here to reconfigure the app for changed settings
}
答案 0 :(得分:1)
强制退出应用时,系统不会保存用户默认值。
我的建议是检查启动时的每个密钥,如果存在,不执行任何操作,如果不存在,则为其设置默认值。
编辑:这是我为许多对象做的事情:
NSArray *keys = [NSArray arrayWithObjects:@"Key 1", @"Key 2", @"Key 3", nil];
NSArray *defaultValues = [NSArray arrayWithObjects:@"Default Value", [UIFont systemFontOfSize:12], [NSNumber numberWithInteger:5], nil];
for(NSInteger i = 0; i < [keys count]; i++){
id object = [[NSUserDefaults standardUserDefaults] objectForKey:[keys objectAtIndex:i];
if(!object)[[NSUserDefaults standardUserDefaults] setObject:[defaultValues objectAtIndex:i] forKey:[keys objectAtIndex:i]];
}