I am creating an app which uses Core Data. I have a flip-side in which the user creates the records which are to be used in the main-view. I fetch the Core Data in my ViewWillAppear in the MainViewController. The problem arises when I run the app on a new device, it returns the error that there is no data in the array.
I populate the array as follows:
/*
Fetch existing events.
Create a fetch request; find the Event entity and assign it to the request; add a sort descriptor; then execute the fetch.
*/
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:@"Child" inManagedObjectContext:_managedObjectContext];
[request setEntity:entity];
// Order the events by creation date, most recent first.
NSSortDescriptor *nameDescriptor = [[NSSortDescriptor alloc] initWithKey:@"name" ascending:NO];
NSSortDescriptor *prizeDescriptor = [[NSSortDescriptor alloc] initWithKey:@"prize" ascending:NO];
NSSortDescriptor *neededDescriptor = [[NSSortDescriptor alloc] initWithKey:@"marblesneeded" ascending:NO];
NSSortDescriptor *colorDescriptor = [[NSSortDescriptor alloc] initWithKey:@"color" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:nameDescriptor,prizeDescriptor,neededDescriptor,colorDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[nameDescriptor release];
[colorDescriptor release];
[prizeDescriptor release];
[neededDescriptor release];
[sortDescriptors release];
// Execute the fetch -- create a copy of the result.
NSError *error = nil;
records = [[self.managedObjectContext executeFetchRequest:request error:&error] retain];
if ([records count] == 0) {
recordsempty = YES;
}
[request release];
And I get the following error:
-[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'
Does anyone have any ideas on helping prevent this crash when a user installs my app from the App Store?
Thanks
The Problem was fixed after I added an if statement to not try to display anything if the array is empty. Then, I used an UIAlertView to direct the user to the flipside.