【发布时间】:2011-09-02 11:52:59
【问题描述】:
我目前正在学习核心数据,并正在编写一个简单版本的苹果核心数据教程(位置)。
下面是addEvent方法的代码:
Event *event = (Event *)[NSEntityDescription insertNewObjectForEntityForName:@"Event" inManagedObjectContext:managedObjectContext];
[event setCreationDate:[NSDate date]];
NSError *error;
if (![managedObjectContext save:&error]) {
// Handle the error.
}
[eventsArray insertObject:event atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:YES];
触发此方法时,我收到 sigabrt 错误。但是我发现,如果我包含苹果的 viewDidLoad 代码,则该错误不再发生,我终生无法弄清楚为什么?
这是阻止错误发生的代码:
- (void)viewDidLoad {
[super viewDidLoad];
// Set the title.
self.title = @"Locations";
// Configure the add and edit buttons.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addEvent)];
self.navigationItem.rightBarButtonItem = addButton;
/*
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:@"Event" inManagedObjectContext:managedObjectContext];
[request setEntity:entity];
// Order the events by creation date, most recent first.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[request setSortDescriptors:sortDescriptors];
[sortDescriptor release];
[sortDescriptors release];
// Execute the fetch -- create a mutable copy of the result.
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[managedObjectContext executeFetchRequest:request error:&error] mutableCopy];
if (mutableFetchResults == nil) {
// Handle the error.
}
// Set self's events array to the mutable array, then clean up.
[self setEventsArray:mutableFetchResults];
[mutableFetchResults release];
[request release];
我错过了什么?我看不到 viewDidLoad 上缺少获取请求是如何导致错误的
谢谢
【问题讨论】:
-
告诉我们更多关于错误的信息 - 你能查明是哪一行导致的吗?
标签: iphone cocoa-touch cocoa core-data