我正在开发ios应用程序,当点击添加按钮时,它会带我到另一个视图控制器来填充我的信息并将它们保存在核心数据中如何获取这些数据并在Tableview中发布任何帮助?
答案 0 :(得分:1)
保存数据(在您从中获取数据的视图控制器中)
你的.m文件中的添加
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
并在保存操作中添加
- (IBAction)savePressed:(id)sender
{
NSManagedObjectContext *context = [self managedObjectContext];
NSManagedObject *newData = [NSEntityDescription insertNewObjectForEntityForName:@"StoredData" inManagedObjectContext:context];
[newData setValue:textField.text forKey:@"dataattribute"];
NSError *error = nil;
if (![context save:&error]) {
NSLog(@"Save Failed! %@ %@", error, [error localizedDescription]);
}
}
表视图控制器中的
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
你视图中的确实出现了
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSManagedObjectContext *moc = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:@"entityName"];
arrayData = [[moc executeFetchRequest:fetchRequest error:nil] mutableCopy];
[self.tableView reloadData];
}
在你的cellForRowAtIndexPath
中- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *cellIdentifier = @"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:cellIdentifier forIndexPath:indexPath];
// Configure the cell...
NSManagedObject *data = [arrayData objectAtIndex:indexPath.row];
[cell.textLabel setText:[NSString stringWithFormat:@"%@", [data valueForKey:@"dataattribute"]]];
return cell;
}