我有一个视图控制器,当用户要求将对象添加到数据库时会触发该控制器。该视图具有文本输入字段以及UIPICKERVIEW。视图加载并正常工作,直到我添加NSMANAGEDOBJECT来存储输入的数据。
标题文件:
`@property (strong, nonatomic) NSManagedObjectContext *managedObjectContext;`
`@property (strong, nonatomic) Training *trainingEvent;`
`@property (retain, nonatomic) NSArray *eventTypes;`
和.m
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.typePicker = [[UIPickerView alloc] init];
if (self.managedObjectContext) {
NSLog(@"managed object context loaded");
} else {
NSLog(@"no managed object context loaded");
}
NSLog(@"event types loaded :%lu", (long unsigned)self.eventTypes.count);
if (self.trainingEvent) {
NSLog(@"training event loaded %@", self.trainingEvent.name);
} else {
//create new event in MOC
NSLog(@"create new training event");
NSEntityDescription *trainingEntityDescription = [NSEntityDescription entityForName:@"Training"
inManagedObjectContext:self.managedObjectContext];
Training *newTrainingEvent = (Training *)[[NSManagedObject alloc] initWithEntity:trainingEntityDescription
insertIntoManagedObjectContext:self.managedObjectContext];
self.trainingEvent = newTrainingEvent;
}
}
当我注释掉else子句时,(在MOC中创建新事件) 视图工作正常。但是如上所述,我收到以下错误:
`*** Terminating app due to uncaught exception 'NSRangeException', reason: '*** -[__NSArrayI objectAtIndex:]: index 0 beyond bounds for empty array'`
附上UIPICKER方法:
-(NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component
{
//cell.textLabel.text = [arrWebServiceList count] > 0 ? [arrWebServiceList objectAtIndex:indexPath.row] : @"DummyText";
NSLog(@"titleForRow %lu", (long)row);
return [self.eventTypes objectAtIndex:row];
}
-(UIView *)pickerView:(UIPickerView *)pickerView viewForRow:(NSInteger)row forComponent:(NSInteger)component reusingView:(UIView *)view
{
UILabel *tView = (UILabel *)view;
NSLog(@"viewForRow %lu", (long)row);
if (!tView) {
tView = [[UILabel alloc] init];
tView.minimumScaleFactor = 0.5;
[tView setFont:[UIFont systemFontOfSize:12.0]];
tView.numberOfLines = 4;
tView.lineBreakMode = NSLineBreakByWordWrapping;
}
tView.text = [self.eventTypes objectAtIndex:row];
return tView;
}
问题:如何创建核心数据对象来存储数据?