localNotification / uiTableView / удалить строку -> ОШИБКА "неверное количество строк" - PullRequest
0 голосов
/ 04 ноября 2011

Это моя ОШИБКА:

Завершение работы приложения из-за необработанного исключения «NSInternalInconsistencyException», причина: «Неверное обновление: недопустимое количество строк в разделе 0. Число строк, содержащихся в существующем разделе после обновления (2), должно быть равно количеству строк содержится в этом разделе до обновления (2), плюс или минус количество строк, вставленных или удаленных из этого раздела (0 вставлено, 1 удалено) и плюс или минус количество строк, перемещенных в или из этого раздела (0 перемещено в , 0 переместился). '

Я знаю, что это значит, но я не могу найти свою ошибку в коде. Я знаю, что я должен использовать только NSMutableArry. Не нормальный NSArray. Это точка, я думаю ...

В моем ч. Файл: NSMutableArray * notifArray, IBOutlet UITableView * myTable;

КОД:

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
        // Return the number of rows in the section.
        return [[[UIApplication sharedApplication] scheduledLocalNotifications] count];

    }

КОД:

// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    static NSString *CellIdentifier = @"Cell";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
    if (cell == nil) {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
    }

    // Configure the cell...

    NSArray *_notifArray = [[UIApplication sharedApplication] scheduledLocalNotifications];
    UILocalNotification *notif = [_notifArray objectAtIndex:indexPath.row];
    <...>

КОД:

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
        // If row is deleted, remove it from the list.
        if (editingStyle == UITableViewCellEditingStyleDelete) {
            [notifArray removeObjectAtIndex:indexPath.row];
            [self.myTable deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];

            [myTable reloadData];
        }
    }

КОД:

- (IBAction) scheduleAlarm:(id) sender {
    [eventText resignFirstResponder];

    NSCalendar *calendar = [NSCalendar autoupdatingCurrentCalendar];

    // Get the current date
    NSDate *pickerDate = [self.datePicker date];

    // Break the date up into components
    NSDateComponents *dateComponents = [calendar components:( NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit ) 
                                                   fromDate:pickerDate];
    NSDateComponents *timeComponents = [calendar components:( NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit ) 
                                                   fromDate:pickerDate];

    // Set up the fire time
    NSDateComponents *dateComps = [[NSDateComponents alloc] init];
    [dateComps setDay:[dateComponents day]];
    [dateComps setMonth:[dateComponents month]];
    [dateComps setYear:[dateComponents year]];
    [dateComps setHour:[timeComponents hour]];
    // Notification will fire in one minute
    [dateComps setMinute:[timeComponents minute]];
    [dateComps setSecond:[timeComponents second]];
    NSDate *itemDate = [calendar dateFromComponents:dateComps];
    [dateComps release];

    localNotification = [[UILocalNotification alloc] init];
    if (localNotification == nil)
        return;
    localNotification.fireDate = itemDate;
    localNotification.timeZone = [NSTimeZone defaultTimeZone];

    // Notification details
    localNotification.alertBody = [eventText text];
    // Set the action button
    localNotification.alertAction = @"View";

    localNotification.soundName = UILocalNotificationDefaultSoundName;
    localNotification.applicationIconBadgeNumber = 1;

    // Specify custom data for the notification
    NSDictionary *infoDict = [NSDictionary dictionaryWithObject:@"someValue" forKey:@"someKey"];
    localNotification.userInfo = infoDict;

    // Schedule the notification
    [[UIApplication sharedApplication] scheduleLocalNotification:localNotification];
    [localNotification release];


    [self.myTable reloadData];
}

Если я изменю эту строку на NSMutabelArray, то я тоже получу ошибку. "Несовместимые типы указателей, инициализирующие" NSMUtableArray "выражением типа" NSArray * "

---> NSArray *_notifArray = [[UIApplication sharedApplication] scheduledLocalNotifications];

Так что я могу сделать, чтобы можно было удалить строку, включая локальное уведомление?

Ответы [ 2 ]

1 голос
/ 05 ноября 2011

ОГРОМНОЕ СПАСИБО !!!

Я думаю, что моя проблема была сначала в неправильном коде ;-), а во-вторых, я забыл, что уведомление, отображаемое подряд, - это ДВА!Поэтому я должен сначала удалить Уведомление и второй раз строку в моем tableView ;-)

Вот мой код - не стесняйтесь; -)

- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
// If row is deleted, remove it from the list.
     if (editingStyle == UITableViewCellEditingStyleDelete)
           {

            // DELETE theNotification defined in (UITableViewCell *)tableView:{}
            [[UIApplication sharedApplication] cancelLocalNotification:notifcation];

            // DELETE theRow
            [notificationsArray removeObjectAtIndex:indexPath.row];
            [tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationLeft];

            [tableView reloadData];
    }    

}

YEEAARRR Я так счастлив ;-) В любом случае, я действительно новичок в кодировании ;-) - Так что, если у кого-то есть лучший способ, не стесняйтесь меня поправлять: -)

0 голосов
/ 04 ноября 2011

Относительно инициализации вы можете создать изменяемый массив следующим образом:

NSMutableArray *_notifArray = [NSMutableArray arrayWithArray:[[UIApplication sharedApplication] scheduledLocalNotifications]];

И вам, вероятно, также необходимо сохранить его.

Что касается удаления строки, мне интересно узнать о вызовеперезагрузить данные.Я не думаю, что это необходимо, поскольку предыдущая строка DeleteRows ... вызывает обновление табличного представления, и мне даже интересно, может ли это быть причиной вашего сообщения.Конечно, он вызывается после DeleteRows, но у нас нет реального способа узнать, как все это упорядочено, и если перезагрузка запрашивает numberOfRows до завершения DeleteRows, то это может вызвать ваше сообщение.

Надеюсь, это поможет.

Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...