在我的iOS应用程序中我尝试执行以下操作:在ViewController中有几个TextFields和一个Save按钮。当用户点击“保存”按钮时,yearTextField的文本必须存储在核心数据属性(todoYear:int32)上。 这是我的Save方法的代码:
- (IBAction)SaveButtonAction:(id)sender {
AppDelegate* appDelegate = [AppDelegate sharedAppDelegate];
NSManagedObjectContext* context = appDelegate.managedObjectContext;
NSManagedObject *favoriteThing = [NSEntityDescription insertNewObjectForEntityForName:@"FavoriteThing" inManagedObjectContext:context];
NSString *todoText = ToDoTextField.text;
NSNumber *todoYear = [yearTextField.text intValue];
NSNumber *todoMonth = [monthTextField.text intValue];
NSNumber *todoDay = [dayTextField.text intValue];
NSNumber *todoHour = [hourTextField.text intValue];
NSNumber *todoMinute = [minuteTextField.text intValue];
NSString *todoUrgent = urgentTextField.text;
NSString *todoColor = colorTextField.text;
[favoriteThing setValue:todoText forKey:@"thingName"];
[favoriteThing setValue:[NSNumber numberWithInt:0] forKey:@"displayOrder"];
[favoriteThing setValue:todoYear forKey:@"todoYear"];
[favoriteThing setValue:todoMonth forKey:@"todoMonth"];
[favoriteThing setValue:todoDay forKey:@"todoDay"];
[favoriteThing setValue:todoHour forKey:@"todoHour"];
[favoriteThing setValue:todoMinute forKey:@"todoMinute"];
[favoriteThing setValue:todoUrgent forKey:@"urgent"];
[favoriteThing setValue:todoColor forKey:@"color"];
NSError *error;
if(! [context save:&error])
{
NSLog(@"Whoopw,couldn't save:%@", [error localizedDescription]);
}
}
这是例外:
self AddToDoViewController * 0x16578680 0x16578680
favoriteThing FavoriteThing_FavoriteThing_ * 0x1650da90 0x1650da90
todoText __NSCFString * @"h" 0x1659f2b0
todoColor __NSCFString * @"Black" 0x16542070
todoUrgent __NSCFString * @"Not urgent" 0x165139e0
todoYear NSNumber * 0x7dd 0x000007dd
todoMinute NSNumber * 0x25 0x00000025
urgentTextField UITextField * 0x165bc2d0 0x165bc2d0
colorTextField UITextField * 0x165b2de0 0x165b2de0
minuteTextField UITextField * 0x165b8380 0x165b8380
'todoText','todoColor','todourgent'的属性是正确的,读取'todoYear'属性的值时会出现错误。 我不知道如何以正确的方式将'todoYear'值正确接受。提前谢谢。
答案 0 :(得分:1)
使用NSNumber
的{{1}}方法:
numberWithInt
或者将这一切组合成NSNumber *todoYear = [NSNumber numberWithInt: [yearTextField.text intValue]];
NSNumber *todoMonth = [NSNumber numberWithInt: [monthTextField.text intValue]];
NSNumber *todoDay = [NSNumber numberWithInt: [dayTextField.text intValue]];
NSNumber *todoHour = [NSNumber numberWithInt: [hourTextField.text intValue]];
NSNumber *todoMinute = [NSNumber numberWithInt: [minuteTextField.text intValue]];
...
NSDate