问题:重启应用后,数据丢失; 我已经阅读了很多关于这个问题的主题,但似乎无法为我的案例找到解决方案。这是我的代码:
id appDelegate = (id)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = [appDelegate managedObjectContext];
Car *newCar = [NSEntityDescription insertNewObjectForEntityForName:@"Car"
inManagedObjectContext:self.managedObjectContext];
newCar.name = self.nameTextField.text;
newCar.c02 = self.carbon.text;
newCar.norma = self.norma.text;
newCar.cc = self.centrimCubi.text;
newCar.age = self.vechime.text;
newCar.costTimbru = self.zaLabel.text;
[self.theCar.managedObjectContext save:nil]; // write to database
self.theCar = newCar;
新对象显示在tableview上,但直到我重新启动应用程序
为了检索我使用的数据:
- (void)setupFetchedResultsController
{
// 1 - Decide what Entity you want
NSString *entityName = @"Car"; // Put your entity name here
NSLog(@"Setting up a Fetched Results Controller for the Entity named %@", entityName);
// 2 - Request that Entity
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:entityName];
// 3 - Filter it if you want
//request.predicate = [NSPredicate predicateWithFormat:@"Person.name = Blah"];
// 4 - Sort it if you want
request.sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:@"name"
ascending:YES
selector:@selector(localizedCaseInsensitiveCompare:)]];
// 5 - Fetch it
self.fetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:self.managedObjectContext
sectionNameKeyPath:nil
cacheName:nil];
[self performFetch];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self setupFetchedResultsController];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = @"Persons Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
Car *person = [self.fetchedResultsController objectAtIndexPath:indexPath];
NSString *fullname = [NSString stringWithFormat:@"%@ € ", person.costTimbru];
cell.textLabel.text = person.name;
cell.detailTextLabel.text = fullname;
//cell.textLabel.text = person.firstname;
return cell;
}