Reputation: 9273
Hello i have two Custom UITableViewCell nib, and i give the option to the users to choose what type of nib choose in the setting, i initialize the custom view cell in this way:
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"MasterViewCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:[[NSUserDefaults standardUserDefaults] valueForKey:@"CustomCellViewKey"] owner:self options:nil];
cell = customCell;
self.customCell = nil;
}
return cell;
}
as you can see i save the choose of the users in a NSUserDefaults that is the name of the xib, but when i return on my view, the cell view is not changed, and i have to exit from the application, close the app from the background, and reopen it, and the new view it's loaded, so there is a method to reload my view without exit from the application?
Upvotes: 0
Views: 976
Reputation: 5707
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;
}
}
}
}
Upvotes: 2