【发布时间】:2014-03-12 22:50:06
【问题描述】:
我正在开发一个 CoreData 应用程序,它在 TableView 中显示 CoreData 的内容。 问题是,添加字符串后,tableView 没有更新 CoreData 的内容。
我试过了:
- (void)viewWillAppear:(BOOL)none
{
[self.tableView reloadData];
}
但没有机会,它不会重新加载。
有任何猜测还是我应该发布更多代码?谢谢你:)
更多代码:)
将字符串保存到 CoreData:
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
AppDelegate *appDelegate =
[[UIApplication sharedApplication] delegate];
NSManagedObjectContext *context =
[appDelegate managedObjectContext];
NSManagedObject *newProduct;
newProduct = [NSEntityDescription
insertNewObjectForEntityForName:@"Products"
inManagedObjectContext:context];
[newProduct setValue: _textField.text forKey:@"productName"];
NSError *error;
[context save:&error];
NSLog(@"Product saved");
}
以及TableViewController的代码:
@implementation CartViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
//Core Data Versuche
/*
Fetch existing events.
Create a fetch request for the Event entity; add a sort descriptor; then execute the fetch.
*/
NSFetchRequest *request = [[NSFetchRequest alloc] initWithEntityName:@"Products"];
[request setFetchBatchSize:20];
// Order the events by creation date, most recent first.
// NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:@"creationDate" ascending:NO];
// NSArray *sortDescriptors = @[sortDescriptor];
// [request setSortDescriptors:sortDescriptors];
// Execute the fetch.
NSError *error;
AppDelegate *delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
NSArray *fetchResult = [delegate.managedObjectContext executeFetchRequest:request error:&error];
if (fetchResult== nil) {
// Replace this implementation with code to handle the error appropriately.
// abort() causes the application to generate a crash log and terminate. You should not use this function in a shipping application, although it may be useful during development.
NSLog(@"Unresolved error %@, %@", error, [error userInfo]);
}
// Set self's events array to a mutable copy of the fetch results.
[self setCartProductsArray:[fetchResult mutableCopy]];
/*
Reload the table view if the locale changes -- look at APLEventTableViewCell.m to see how the table view cells are redisplayed.
*/
__weak UITableViewController *cell = self;
[[NSNotificationCenter defaultCenter] addObserverForName:NSCurrentLocaleDidChangeNotification object:nil queue:[NSOperationQueue mainQueue] usingBlock:^(NSNotification *note) {
[cell.tableView reloadData];
}];
// Ende Core Data Versuche
}
- (void)viewWillAppear:(BOOL)none
{
[self.tableView reloadData];
}
【问题讨论】:
-
该表不更新核心数据。您更新核心数据,然后更新表以反映新数据。
-
是的,发布更多代码。您尝试更新 Core Data 的方式以及填充表格单元格的方式。
-
在
viewWillAppear中不需要[self.tableView reloadData];。但是您现在需要做的就是在fetchResult更改时更新,因此NSFetchedResultsController。 -
您似乎使用了我对上一个问题的回答中的代码。请问您为什么在确认答案有帮助后删除了该问题?
标签: ios uitableview core-data