Reputation: 87
I'm working on ios application that when clicking add button it takes me to another view controller to fill my information and save them in core data how can i fetch this data and post it in Tableview any help ?
Upvotes: 0
Views: 125
Reputation: 93
To save the data (in your view controller where you get the data from)
in your .m file add
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
and in your save action add
- (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]);
}
}
in your table view controller
- (NSManagedObjectContext *)managedObjectContext
{
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:@selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
in your view did appear
- (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];
}
And in your 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;
}
Upvotes: 1