Странное поведение с UITableView

#ios #objective-c #uitableview #nsuserdefaults

#iOS #objective-c #uitableview #nsuserdefaults

Вопрос:

Я вижу какое-то странное поведение с моим UITableViewController, показанным с помощью Popover.

Это мой код ViewController:

 @interface PrepareViewController ()
{
NSMutableArray *_objects;
NSString *savingKey;
}

@end

@implementation PrepareViewController

- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
    // Custom initialization
}
return self;
}

- (void)awakeFromNib
{
self.clearsSelectionOnViewWillAppear = NO;
self.preferredContentSize = CGSizeMake(320.0, 600.0);
[super awakeFromNib];
}

- (void)viewDidLoad
{
[super viewDidLoad];

// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;

// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
self.navigationItem.leftBarButtonItem = self.editButtonItem;

// Register a class or nib file using registerNib:forCellReuseIdentifier
// o registerClass:forCellReuiseIdentifier: method before calling this method
[self.tableView registerClass:[UITableViewCell class] forCellReuseIdentifier:@"Cell"];

// Setup savingKey
savingKey = @"prepareKey";

// Load the items from NSUserDefaults
_objects = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:savingKey]];

        [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(defaultsChanged:) name:NSUserDefaultsDidChangeNotification object:nil];
}

- (void)defaultsChanged:(NSNotification *)notification {
// Setup savingKey
savingKey = @"prepareKey";

// Load the items from NSUserDefaults
_objects = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:savingKey]];

// Reload the tableView
[self.tableView reloadData];
}

- (void)dealloc {
[[NSNotificationCenter defaultCenter] removeObserver:self];
}

- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}

-(void)saveSummaries {
// Save the summaries to NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:_objects forKey:savingKey];
}

- (void)viewDidAppear:(BOOL)animated{
[super viewDidAppear:animated];
}


#pragma mark - Table view data source

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return _objects.count;
}

// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];

NSString *object = _objects[indexPath.row];
cell.textLabel.text = [object description];
return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Open the chosen item
MyManager *sharedManager = [MyManager sharedManager];
sharedManager.openSummary = _objects[indexPath.row];

// Modal to SummaryViewController
[self performSegueWithIdentifier:@"summarySegue" sender:self];
}

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
    [_objects removeObjectAtIndex:indexPath.row];
    [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];

    // Delete the associated information
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:[NSString stringWithFormat:@"%@%@", _objects[indexPath.row], @"-summary"]];

    NSLog(@"delete3");

    // Save the new list of combined summaries
    [[NSUserDefaults standardUserDefaults] setObject:_objects forKey:@"prepareKey"];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
    // Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}

@end
  

Проблема:
Когда пользователь нажимает «Удалить» в режиме редактирования, анимация не появляется, и выбранный элемент возвращается на место без какой-либо анимации, а элемент остается не удаленным. Я проверил, что вызывается метод удаления — есть идеи, в чем может быть проблема?

Спасибо за помощь!

Ответ №1:

Я думаю, это из-за этого:

 - (void)defaultsChanged:(NSNotification *)notification {
// Setup savingKey
savingKey = @"prepareKey";

// Load the items from NSUserDefaults
_objects = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:savingKey]];

// Reload the tableView
[self.tableView reloadData]; <------- manual reload without animations
}
  

При изменении значений по умолчанию в:

 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
  

этот код выполняется.

Комментарии:

1. О, я понимаю! Могу ли я решить это, просто создав BOOL для случаев, когда я хочу, чтобы defaultsChanged игнорировал уведомление?

2. Вы можете решить это таким образом, или я думаю, что лучше не делать этого с помощью автоматического уведомления, просто вызывайте это специально, когда вам нужно напрямую — я имею в виду обновление источника данных и перезагрузку таблицы. Если вы когда-нибудь измените источник данных на базу данных или загруженный из Интернета — его проще заменить 🙂