Any idea why these defaults would come back null?
Occasionally, especially if I have played with settings or the app has been force quit all the formatting is messed up because these values come back 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:Cel开发者_开发知识库lIdentifier] 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;
}
Edit with code from InAppSettingsKit, in my rootview controller I do this:
- (void)settingsViewControllerDidEnd:(IASKAppSettingsViewController*)sender {
[[NSUserDefaults standardUserDefaults] synchronize];
[self dismissModalViewControllerAnimated:YES];
// your code here to reconfigure the app for changed settings
}
When you force quit the app, the user defaults are not saved.
My suggestion would be to check for every key at launch, if it exists, do nothing, if it doesn't, set a default value to it.
EDIT: This is how I'd do it for many objects:
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]];
}
精彩评论