Search code examples
iosarrayscore-datansrangeexception

RangeException on Array objectAtIndex <huge number> #Core Data


Novice to Programming**

Getting a "beyond bounds" NSRangeException when trying to access an object from a mutable array. The error is showing a long number for the objectAtIndex, but the array only currently has three objects.

This is the error message: Terminating app due to uncaught exception 'NSRangeException', reason: '* -[__NSArrayM objectAtIndex:]: index 2147483647 beyond bounds [0 .. 2]'

I am using Core Data.

The app is crashing when I select the first row of a tableview that is populated via Core Data.

The mutable array is called "allDates".

The code that seems to be causing it is in a prepareForSegue method here:

Part of DateTableViewController.m

- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{

NSString *segueIdentifier = [segue identifier];
    if ([segueIdentifier isEqualToString:@"showDetails"])
    {
        NSManagedObjectContext *context = [self managedObjectContext];

        NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
        NSEntityDescription *entity = [NSEntityDescription entityForName:@"Date"
                                                  inManagedObjectContext:context];
        [fetchRequest setEntity:entity];


        self.allDates = [[context executeFetchRequest:fetchRequest error:nil] mutableCopy];
        DateIdeaDetailViewController *vc = [segue destinationViewController];

        NSIndexPath *selectedRowIndexPath = [self.tableView indexPathForSelectedRow];

         NSUInteger index = [allDates indexOfObject:selectedRowIndexPath];
        //edited based on WilliamFalcon added "(int)"
        _string = [NSMutableString stringWithFormat:@"%@", [allDates[(int)index] valueForKey:@"date_idea"]];

       vc.dateIdeaLabelText = self.string;

    }

}

DateTableViewController.h

#import <UIKit/UIKit.h>
#import "LifeBook.h"
#import "LifeBookAppDelegate.h"
#import "DateIdeaDetailViewController.h"

@interface DateTableViewController : UITableViewController 

@property (strong, nonatomic) NSMutableArray *allDates;
@property (readonly, strong, nonatomic) NSManagedObjectContext *managedObjectContext;
@property (readonly, strong, nonatomic) NSManagedObjectModel *managedObjectModel;
@property (readonly, strong, nonatomic) NSPersistentStoreCoordinator *persistentStoreCoordinator;
@property (weak, nonatomic) IBOutlet UITableViewCell *tableViewCell1;
@property (strong, nonatomic) NSMutableString *string;

@property (strong, nonatomic) NSString *label;


@end

Please let me know if this is a stupid question. Resources of any type are appreciated.

Thanks for any help


Solution

  • It looks like you are asking your array for the index of the indexpath. I dont think that's an array of indexpaths...

    You should just do allDates[selectedRowIndexPath.row].

    Also try to break up that line into parts so you can debug better.