[英]iOS CoreData Array only displaying when I relaunch the application
I have a simple Grocery List app where I add items to the list. 我有一个简单的“杂货清单”应用,可以在其中添加商品。 I want to save these items with Core Data so that the data is saved when the app is terminated.
我想将这些项目与“核心数据”一起保存,以便在终止应用程序时保存数据。
I simply want to display all data, so if I understand correctly I don't need to implement an NS-FetchedResultsController for this. 我只想显示所有数据,所以如果我理解正确,则不需要为此实现NS-FetchedResultsController。
Right now, items are successfully adding in my CoreData, but the list only refreshes when I exit the app and re-open it. 现在,项已成功添加到我的CoreData中,但是列表仅在我退出应用并重新打开时刷新。
So far I've tried putting [self.tableView reloadData]
, [[self tableView] reloadData]
and [self.tableView reloadRowsAtIndexPaths:groceryArray withRowAnimation:YES];
到目前为止,我已经尝试将
[self.tableView reloadData]
, [[self tableView] reloadData]
和[self.tableView reloadRowsAtIndexPaths:groceryArray withRowAnimation:YES];
in all the locations I could think of, including the viewDidLoad method, the unwindToSegue method that's coming from the Add Grocery Item List view controller, and also implementing a viewWillAppear method as well. 在我能想到的所有位置,包括viewDidLoad方法,来自Add Grocery Item List视图控制器的unwindToSegue方法,还实现了viewWillAppear方法。
My mainAppDelegate code is straight from Apple and a tutorial... so I don't think this code is the problem. 我的mainAppDelegate代码直接来自Apple和一个教程...所以我认为这不是问题所在。 All properties and files are imported correctly.
所有属性和文件均已正确导入。
My data entity is entitled "Item" and i have one single attribute titled "toDoItems" (type: string). 我的数据实体的标题为“ Item”,我有一个标题为“ toDoItems”的单一属性(类型:字符串)。
my TableViewController code which displays the list of data (and is not refreshing): 我的TableViewController代码显示数据列表(并且不刷新):
@interface XYZToDoListViewController ()
@end
@implementation XYZToDoListViewController
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
@synthesize groceryArray;
- (IBAction)unwindToList:(UIStoryboardSegue *)segue
{
[[self tableView] reloadData];
}
- (void)viewDidLoad
{
[super viewDidLoad];
mainAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
_managedObjectContext = [appDelegate managedObjectContext];
NSFetchRequest *request = [[NSFetchRequest alloc]init];
NSEntityDescription *items = [NSEntityDescription entityForName:@"Item" inManagedObjectContext:_managedObjectContext];
[request setEntity:items];
NSError *error = nil;
NSMutableArray *mutableFetchResults = [[_managedObjectContext executeFetchRequest:request error:&error]mutableCopy]; if (mutableFetchResults == nil){
//handle error
}
[self setGroceryArray:mutableFetchResults];
[[self tableView] reloadData];
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
NSManagedObject *eventToDelete = [ groceryArray objectAtIndex:indexPath.row];
[_managedObjectContext deleteObject: eventToDelete];
[groceryArray removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
NSError *error = nil;
if (![_managedObjectContext save:&error])
{ //handle error
}
}
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection: (NSInteger)section
{
return [groceryArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"ListPrototypeCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
Item *items = (Item *) [groceryArray objectAtIndex:indexPath.row];
cell.textLabel.text = [items toDoItems];
return cell;
}
@end
My Add New Item view controller: 我的“添加新项”视图控制器:
@interface XYZAddItemViewController ()
@property (strong, nonatomic) IBOutlet UIBarButtonItem *doneButton;
@end
@implementation XYZAddItemViewController
@synthesize textField;
@synthesize managedObjectContext = _managedObjectContext;
@synthesize managedObjectModel = _managedObjectModel;
@synthesize persistentStoreCoordinator = _persistentStoreCoordinator;
- (void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender
{
Item *item = [NSEntityDescription insertNewObjectForEntityForName:@"Item" inManagedObjectContext:_managedObjectContext];
[item setToDoItems:textField.text];
NSLog (@"Item Added");
NSError *error = nil;
if (![_managedObjectContext save:&error])
{ //handle error }
textField.text = NULL;
}
}
- (BOOL)shouldPerformSegueWithIdentifier:(NSString *)segue sender:(id)sender {
if (self.textField.text.length > 0)
{
return YES;
}
else {
return NO;
}
}
- (void)viewDidLoad
{
[super viewDidLoad];
mainAppDelegate *appDelegate = [[UIApplication sharedApplication]delegate];
_managedObjectContext = [appDelegate managedObjectContext];
self.navigationController.view.backgroundColor =
[UIColor colorWithPatternImage:[UIImage imageNamed:@"bg_white.png"]];
self.view.backgroundColor = [UIColor clearColor];
}
-(BOOL)textFieldShouldReturn:(UITextField *)textField{
[textField resignFirstResponder];
return YES;
}
@end
What do I need to change to get the table view controller to refresh? 我需要更改什么才能刷新表视图控制器?
You have to execute the fetch request again after an item has been added, and assign the result to your data source array groceryArray
, before calling reloadData
. 添加项目后,您必须再次执行获取请求,然后将结果分配给数据源数组
groceryArray
数组,然后再调用reloadData
。
Otherwise reloadData
has only the effect that the same old data is displayed again. 否则,
reloadData
仅具有再次显示相同的旧数据的效果。
(This is what a fetched results controller would manage for you.) (这是获取的结果控制器将为您管理的。)
The data for your UITableView comes from groceryArray. UITableView的数据来自杂货店数组。
You are inserting the objects correctly into CoreData, but your tableView is still looking to the groceryArray that you fetched at the start. 您正在正确地将对象插入CoreData,但是tableView仍在寻找开始时获取的grossantArray。
So when you add something, you need to run the fetch request again, save it to groceryArray, and THEN do a reloadData. 因此,当您添加内容时,您需要再次运行获取请求,将其保存到杂货数组,然后执行reloadData。 That way it should reflect the changes.
这样,它应该反映出变化。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.