数组中没有数据

时间:2011-11-12 03:52:32

标签: iphone objective-c ios xcode core-data

我正在创建一个使用Core Data的应用。我有一个翻转方,用户在其中创建将在主视图中使用的记录。我在MainViewController中的ViewWillAppear中获取Core Data。当我在新设备上运行应用程序时出现问题,它返回错误,表明数组中没有数据。

我按如下方式填充数组:

/*
 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];

我收到以下错误:

-[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'

当用户从App Store安装我的应用程序时,有没有人有任何关于帮助防止此崩溃的想法?

由于

1 个答案:

答案 0 :(得分:0)

在添加if语句后,如果数组为空则不尝试显示任何内容,问题得到解决。然后,我使用UIAlertView将用户引导到另一侧。