Index out of bounds when trying to delete a row (cell) from a section and update table (Xcode,Objective-c)

user3305222

I have a tableview grouped by sections, and sorted by dates, every section is basically a day, every row is an appointment/event on that day. I get my events from an nsmutablearray, and they have a "startDate" property by which i sort the table. I'm having trouble trying to delete a row from a sections.

-If i have 1 section with 5 rows , it's ok i can delete each of them individually and the last one will also delete the section.

-If i have more than 1 section , when i try to delete the last row in a section, it crashes.

Here is my code:

 @interface AgendaViewController ()
@property (nonatomic,strong) NSString *path;
@property (strong, nonatomic) NSMutableDictionary *sections;
@property (strong, nonatomic) NSMutableArray *sortedDays;
@property (strong, nonatomic) NSDateFormatter *sectionDateFormatter;
@property (strong, nonatomic) NSDateFormatter *cellDateFormatter;
@end

@implementation AgendaViewController
@synthesize events = _events;
-(IBAction)menuButtonTapped:(id)sender{
    [self.slidingViewController anchorTopViewToRightAnimated:YES];

}
-(IBAction)unwindToAgenda:(UIStoryboardSegue *)segue{
    AddAgendaEntryViewController *source = [segue sourceViewController];
    AgendaEntry *event = source.agendaEntry;
    if (event){
        [self.events addObject:event];
        [self saveList];
        [self createSections];
        [self.tableView reloadData];
    }

}

- (void)saveList
{
    [NSKeyedArchiver archiveRootObject:self.events toFile:self.path];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    self.path = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
    self.path = [self.path stringByAppendingPathComponent:@"TodoList.txt"];
    NSFileManager *fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:self.path]) {
        self.events = [[NSMutableArray alloc] init];
    } else {
        self.events = [[NSKeyedUnarchiver unarchiveObjectWithFile:self.path] mutableCopy];
    }

    [self setMenuGesture];
    [self fetchEvents];


    [self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleSingleLine];
    self.tableView.separatorColor = [UIColor colorWithRed:224.0/255.0 green:224.0/255.0 blue:224.0/255.0 alpha:1.0f];

    [self createSections];
        //date formatteri

        self.sectionDateFormatter = [[NSDateFormatter alloc] init];
        [self.sectionDateFormatter setDateStyle:NSDateFormatterLongStyle];
        [self.sectionDateFormatter setTimeStyle:NSDateFormatterNoStyle];

        self.cellDateFormatter = [[NSDateFormatter alloc] init];
        [self.cellDateFormatter setDateStyle:NSDateFormatterNoStyle];
        [self.cellDateFormatter setTimeStyle:NSDateFormatterShortStyle];

    }


-(void)createSections{
    self.sections = nil;
    self.sections = [[NSMutableDictionary alloc]init];
    for (AgendaEntry *entry in self.events){
        NSDate *dateRepresentingThisDay = [self dateAtBeginningOfDayForDate:entry.startDate];
        NSMutableArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
        if(eventsOnThisDay == nil){
            eventsOnThisDay = [NSMutableArray array];
            [self.sections setObject:eventsOnThisDay forKey:dateRepresentingThisDay];

        }
        [eventsOnThisDay addObject:entry ];

        NSArray *unsortedDays =  [self.sections allKeys];

        self.sortedDays = [[unsortedDays sortedArrayUsingSelector:@selector(compare:)] mutableCopy];}

        NSLog(@"NUMBER OF SECTIONS IN TABLEVIEW: %lu",(unsigned long)[self.sections count]);
   // [self.tableView reloadData];
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return [self.sections count];
}







- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];

}


-(void)fetchEvents{
    //Apel catre webserver pentru eventuri.
}

-(void)setEvents:(NSMutableArray *)events{
    _events = events;
    [self.tableView reloadData];
}

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

#pragma mark - Table view data source

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:section];
    NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
    return [eventsOnThisDay count];
}

/*- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
    NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:section];
    NSString *title = [self.sectionDateFormatter stringFromDate:dateRepresentingThisDay];
    return title;
}*/
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger) section{

    UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0, 0, tableView.frame.size.width, 15)];
    UILabel *lbl = [[UILabel alloc] initWithFrame:CGRectMake(5, 5, self.view.frame.size.width, 15)];
    lbl.backgroundColor = [UIColor clearColor];
    lbl.textAlignment = NSTextAlignmentCenter;
    lbl.font = [UIFont systemFontOfSize:12];

    NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:section];
    NSString *title = [self.sectionDateFormatter stringFromDate:dateRepresentingThisDay];
    lbl.text = title;

    [view addSubview:lbl];
    [view setBackgroundColor:[UIColor colorWithRed:166/255.0 green:177/255.0 blue:186/255.0 alpha:0.3]]; //your background color...
    return view;
}


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

    // Configure the cell..
    //AgendaEntry *event = [self.events objectAtIndex:indexPath.row];

    NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:indexPath.section];
    NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
    AgendaEntry *event = [eventsOnThisDay objectAtIndex:indexPath.row];

  UIImageView *mappin = (UIImageView *)[cell viewWithTag:4] ;
    mappin.image  = [UIImage imageNamed:@"map_pin"];

    UILabel *companyName = (UILabel *)[cell viewWithTag:1];
    companyName.text = event.companyName;

    UILabel *eventType = (UILabel *) [cell viewWithTag:3];
    eventType.text = event.eventType;

    UILabel *dateOfEvent = (UILabel *) [cell viewWithTag:2];

    dateOfEvent.text = [self.cellDateFormatter stringFromDate:event.startDate];
    return cell;
}


- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if (editingStyle == UITableViewCellEditingStyleDelete) {
        // Delete the row from the data source

        [self.events removeObjectAtIndex:indexPath.row];
        [self createSections];

        [self saveList];

        [tableView beginUpdates];
        NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:indexPath.section];
        NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
        if ([eventsOnThisDay count] > 0){

        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
        }else{
        [tableView deleteSections:[NSIndexSet indexSetWithIndex:indexPath.section]
                 withRowAnimation:UITableViewRowAnimationFade];


}
        [tableView endUpdates];
    }
    [self.tableView reloadData];
}

-(NSMutableArray *)sortedDays{
    if (!_sortedDays) _sortedDays = [[NSMutableArray alloc]init];
    return _sortedDays;
}


-(void)setMenuGesture{
    id<ECSlidingViewControllerDelegate> transition = self.zoomAnimationController ;
    self.slidingViewController.delegate = transition;
    self.slidingViewController.topViewAnchoredGesture = ECSlidingViewControllerAnchoredGestureTapping | ECSlidingViewControllerAnchoredGesturePanning;
    self.slidingViewController.customAnchoredGestures = @[];

  //  [self.navigationController.view addGestureRecognizer:self.slidingViewController.panGesture];
}

- (ZoomAnimationController *)zoomAnimationController {
    if (_zoomAnimationController) return _zoomAnimationController;

    _zoomAnimationController = [[ZoomAnimationController alloc] init];

    return _zoomAnimationController;
}

-(NSMutableArray *)events{
    [self sortEvents];
    return _events;
}
/*- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 30;
}*/

- (NSDate *)dateAtBeginningOfDayForDate:(NSDate *)inputDate
{
    // Use the user's current calendar and time zone
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSTimeZone *timeZone = [NSTimeZone systemTimeZone];
    [calendar setTimeZone:timeZone];

    // Selectively convert the date components (year, month, day) of the input date
    NSDateComponents *dateComps = [calendar components:NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit fromDate:inputDate];

    // Set the time components manually
    [dateComps setHour:0];
    [dateComps setMinute:0];
    [dateComps setSecond:0];

    // Convert back
    NSDate *beginningOfDay = [calendar dateFromComponents:dateComps];
    return beginningOfDay;
}


-(void)sortEvents{
    NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"startDate" ascending:TRUE];
    [_events sortUsingDescriptors:[NSArray arrayWithObject:sortDescriptor]];

}
@end

The error i get:

Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayM objectAtIndex:]: index 1 beyond bounds [0 .. 0]'`

HRM

It seems like the logic in deleteForRowAtIndexPath causes the issue. What you are doing is just deleting from self.events based on indexPath.row. But your self.events and the eventsOnThisDay array may not be holding same index when you have more than 1 section.

I recommend you to delete the item in same way as you are loading it to tableView. For example, in deleteRowAtIndexPath,

NSDate *dateRepresentingThisDay = [self.sortedDays objectAtIndex:indexPath.section];
NSArray *eventsOnThisDay = [self.sections objectForKey:dateRepresentingThisDay];
[eventsOnThisDay removeObjectAtIndex:indexPath.row];
//If there are no more events on this day, then just delete the section also.
if([eventsOnThisDay count] == 0){
   [self.sections removeObjectForKey:dateRepresentingThisDay];
   [self.sortedDays removeObjectAtIndex:indexPath.section];
}
[self.tableView reloadData];
//You should also update your self.events list also accordingly.

Hope this helps.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related

From Dev

Index out of bounds in Bitmap.SetSourceInternal, when trying to load an image

From Dev

Index out of bounds error accessing dataset table row

From Dev

Index out of bounds error accessing dataset table row

From Dev

Error when trying to delete a table row (javascript)

From Dev

Why am I getting "FROM expression expected" from SQLAlchemy when I'm trying to update a row in a table?

From Dev

Why python numpy.delete does not raise indexError when out-of-bounds index is in np array

From Dev

Remove / delete selected cells from UICollectionView causes index out of bounds [sometimes]

From Dev

Index is out of bounds when using for loop

From Dev

getting index out of bounds when the array is not empty

From Dev

Array index out of bounds error when using "."

From Dev

Index out of bounds when using an copy of the variable

From Dev

UITableView Section Index overlapping row delete button

From Dev

UITableView Section Index overlapping row delete button

From Dev

C# ColorMatrix Index out of Bounds

From Dev

C# Index out of bounds of array

From Dev

C# Array of List Index out of bounds

From Dev

Error 'Invalid update: invalid number of rows in section 0' attempting to delete row in table

From Dev

trying to get id from table row to perform update

From Dev

Delete row in a table by clicking cell in another table

From Dev

Getting cell pointer from section and row at tableView

From Dev

Can't update or delete row from table (Postgres)

From Dev

Read SQl table row by row and update a cell

From Dev

range out of bounds size 4 objective c

From Dev

Give section index without any section in table view in objective C for sorting single NSArray?

From Dev

Fade UITableView section index in and out when scrolling

From Dev

c# Keep getting index is out of bounds when using "array[x].contains(array2[y]"

From Dev

"Attempt to delete row from section 1, but there are only 1 sections before update"

From Dev

subListString Index out of bounds

From Dev

Index out of bounds in a Spinner

Related Related

  1. 1

    Index out of bounds in Bitmap.SetSourceInternal, when trying to load an image

  2. 2

    Index out of bounds error accessing dataset table row

  3. 3

    Index out of bounds error accessing dataset table row

  4. 4

    Error when trying to delete a table row (javascript)

  5. 5

    Why am I getting "FROM expression expected" from SQLAlchemy when I'm trying to update a row in a table?

  6. 6

    Why python numpy.delete does not raise indexError when out-of-bounds index is in np array

  7. 7

    Remove / delete selected cells from UICollectionView causes index out of bounds [sometimes]

  8. 8

    Index is out of bounds when using for loop

  9. 9

    getting index out of bounds when the array is not empty

  10. 10

    Array index out of bounds error when using "."

  11. 11

    Index out of bounds when using an copy of the variable

  12. 12

    UITableView Section Index overlapping row delete button

  13. 13

    UITableView Section Index overlapping row delete button

  14. 14

    C# ColorMatrix Index out of Bounds

  15. 15

    C# Index out of bounds of array

  16. 16

    C# Array of List Index out of bounds

  17. 17

    Error 'Invalid update: invalid number of rows in section 0' attempting to delete row in table

  18. 18

    trying to get id from table row to perform update

  19. 19

    Delete row in a table by clicking cell in another table

  20. 20

    Getting cell pointer from section and row at tableView

  21. 21

    Can't update or delete row from table (Postgres)

  22. 22

    Read SQl table row by row and update a cell

  23. 23

    range out of bounds size 4 objective c

  24. 24

    Give section index without any section in table view in objective C for sorting single NSArray?

  25. 25

    Fade UITableView section index in and out when scrolling

  26. 26

    c# Keep getting index is out of bounds when using "array[x].contains(array2[y]"

  27. 27

    "Attempt to delete row from section 1, but there are only 1 sections before update"

  28. 28

    subListString Index out of bounds

  29. 29

    Index out of bounds in a Spinner

HotTag

Archive