Reload Nib of custom UITableViewCell at runtime-Collection of common programming errors
So, the way NSUserDefaults works is that even if you use setValue:forKey: (or one of the other setter convenience methods), it doesn’t actually get written out immediately. The OS tries to optimize the saving of that plist by only doing so after a period of time, when the app quits, etc. Prior to that time, the value you set is simply cached to keep the OS from having to open and close the database numerous times. So when you try and get the value out for the cell, it’s going to the database and retrieving what may be an old value. When you quit the app, NSUserDefaults writes out the new value you set, and when you come back, you’re getting that correct value.
To “force” NSUserDefaults to write to the database immediately, try calling synchronize immediately after you set the value based on the user’s input. This will write out to the database, so when you call your valueForKey: method, you should get the correct thing back.
UPDATE: I would also restructure this method’s logical flow. First of all, if you are unloading two cells from two different nibs, they need two different reuse identifiers. Otherwise your tableview is out hunting for cell1’s to reuse when it really needs cell2’s. Try something like this:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
NSString *nibName = [[NSUserDefaults standardUserDefaults] valueForKey:@"CustomCellViewKey"];
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:nibName];
if (!cell) {
NSArray *nibArray = [[NSBundle mainBundle] loadNibNamed:nibName owner:self options:nil];
for (id obj in nibArray) {
if ([obj isKindOfClass:[UITableViewCell class]]) {
cell = obj;
break;
}
}
}
}