ios Core Data - 我的保存按钮不起作用
Posted
技术标签:
【中文标题】ios Core Data - 我的保存按钮不起作用【英文标题】:ios Coredata - my savebutton is not working 【发布时间】:2012-11-18 04:23:12 【问题描述】:我正在尝试为我的 CoreData 项目制作一个保存按钮,通常我没有任何问题。但这次我没有看到它保存到 SQL 文件(在 FireFox 中使用 SQLite),也无法将数据拉回 UITableView。
没有错误或警告。有人可以帮我解决周日下午(新西兰时间)阴天的问题吗??
- (IBAction)saveDataAction:(id)sender
//Instantiating the Entity with a pointer and giving it a mission.
NSString *details = @"Details";
NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:details inManagedObjectContext:[self managedObjectContext]];
int yearOfBirth = [_yearTxtField.text intValue]; //Converting the value from a String into an int
NSNumber *year = [NSNumber numberWithInt:yearOfBirth]; //Converting the int into a NSNumber
//Setting each textField value to an attribute in the Entity.
[newObject setValue:_nameTxtField.text forKey:@"name"];
[newObject setValue:_streetTxtField.text forKey:@"streetName"];
[newObject setValue:_cityTxtField.text forKey:@"cityName"];
[newObject setValue:year forKey:@"yearOfBirth"];
//This log just shows what has been added to the database.
//NSLog(@"Details Save:\n\n Name: %@\n StreetName: %@\n CityName: %@\n Year of birth: %@", details.name, details.streetName, details.cityName, details.yearOfBirth);
【问题讨论】:
在上下文中添加对象后需要保存上下文。试试我的代码 【参考方案1】:- (IBAction)saveDataAction:(id)sender
//Instantiating the Entity with a pointer and giving it a mission.
NSString *details = @"Details";
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newObject = [NSEntityDescription insertNewObjectForEntityForName:details inManagedObjectContext:context];
int yearOfBirth = [_yearTxtField.text intValue]; //Converting the value from a String into an int
NSNumber *year = [NSNumber numberWithInt:yearOfBirth]; //Converting the int into a NSNumber
//Setting each textField value to an attribute in the Entity.
[newObject setValue:_nameTxtField.text forKey:@"name"];
[newObject setValue:_streetTxtField.text forKey:@"streetName"];
[newObject setValue:_cityTxtField.text forKey:@"cityName"];
[newObject setValue:year forKey:@"yearOfBirth"];
NSError *error;
if (![context save:&error])
NSLog(@"Whoops couldn't save new object");
//This log just shows what has been added to the database.
//NSLog(@"Details Save:\n\n Name: %@\n StreetName: %@\n CityName: %@\n Year of birth: %@", details.name, details.streetName, details.cityName, details.yearOfBirth);
【讨论】:
一旦你完成删除、更新或插入,你总是需要保存上下文。不要忘记 :-) @JeffKranenburg。以上是关于ios Core Data - 我的保存按钮不起作用的主要内容,如果未能解决你的问题,请参考以下文章