I want to implement a UITableView using core data and when I press a Trash button in my ViewController, I can see all the delete buttons on the right of all the cells without the swipe gesture. But When i enabled the editing mode only Delete Button should have to be displayed on the right side
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSManagedObjectContext *context = [self managedObjectContext];
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete object from database
[context deleteObject:[self.notes objectAtIndex:indexPath.row]];
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Can't Delete! %# %#", error, [error localizedDescription]);
return;
}
// Remove note from table view
[self.notes removeObjectAtIndex:indexPath.row];
[self.tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
can anyone suggest me how it is possible
Edited :
Write Following Code :
-(void) yourMethodName:(UIButton *) sender
{
if(self.editing)
{
[super setEditing:NO animated:NO];
[self.tblView setEditing:NO animated:NO];
[self.tblView reloadData];
}
else
{
[super setEditing:YES animated:YES];
[self.tblView setEditing:YES animated:YES];
[self.tblView reloadData];
}
}
Related
I have a tableview in my app that displays the entries in an underlying COreData entity. Each row in the entity is a unique-ID of a message sender and their message count.
When view first loads, the Tableview correctly displays all the entries in the CoreData entity that is linked to the NSFetchedResultsController tied to the Table View. But when the view is being shown and a new element is added to the CoreData entity or modified (due to an incoming message), the table view gets completely messed up. It starts to show the same element of the table twice. It never expands the number of rows even when new element is inserted etc etc.
When I do a NSLog of the elements in the underlying CoreData entity, I see that they are updated correctly and there is no duplication. So, it is not clear why the NSFetchedResultsController is not displaying the right thing.
The delegate code is all boiler plate from Apple documentation. The view controller code is below. Any pointers will be greatly appreciated.
#implementation TweetListTableViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Uncomment the following line to preserve selection between presentations.
// self.clearsSelectionOnViewWillAppear = NO;
// Uncomment the following line to display an Edit button in the navigation bar for this view controller.
// self.navigationItem.rightBarButtonItem = self.editButtonItem;
self.title = #"Tweets";
AppDelegate *app = (AppDelegate*)[[UIApplication sharedApplication] delegate];
self.managedObjectContext = app.managedObjectContext;
[self initializeFetchedResultsController] ;
}
- (void)viewDidUnload {
self.fetchedResultsController = nil;
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.tableView performSelectorOnMainThread:#selector(reloadData) withObject:nil waitUntilDone:NO];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - NSFetchedResultsController helper methods
- (void)initializeFetchedResultsController
{
NSFetchRequest *request = [NSFetchRequest fetchRequestWithEntityName:#"UniqueUserTable"];
NSSortDescriptor *timeSort = [NSSortDescriptor sortDescriptorWithKey:#"mostRecentSentTime" ascending:NO] ;
NSSortDescriptor *uidSort = [NSSortDescriptor sortDescriptorWithKey:#"sendingUserID" ascending:YES] ;
[request setSortDescriptors:[NSArray arrayWithObjects:timeSort, uidSort, nil]];
[self setFetchedResultsController:[[NSFetchedResultsController alloc] initWithFetchRequest:request managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:nil]];
[[self fetchedResultsController] setDelegate:self];
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Failed to initialize FetchedResultsController: %#\n%#", [error localizedDescription], [error userInfo]);
abort();
}
}
#pragma mark - Table view data source
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath*)indexPath
{
UniqueUserTable *uutableEntry = [[self fetchedResultsController] objectAtIndexPath:indexPath];
// Populate cell from the NSManagedObject instance
cell.textLabel.text=uutableEntry.sendingUserID ;
cell.detailTextLabel.text=[NSString stringWithFormat:#"%# tweets",uutableEntry.numberOfMessagesSent] ;
DDLogVerbose(#"Row %ld being updated with values text = %#, detailText=%#",(long)indexPath.row,cell.textLabel.text,cell.detailTextLabel.text) ;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"TweetCelldentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.font = [UIFont systemFontOfSize:18.0];
if (!cell)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
DDLogVerbose(#"Initializing cell") ;
}
// Set up the cell
//To get section use indexPath.section
//To get row use indexPath.row
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[[self fetchedResultsController] sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id< NSFetchedResultsSectionInfo> sectionInfo = [[self fetchedResultsController] sections][section];
DDLogVerbose(#"Number of rows to show in table = %ld",(unsigned long)[sectionInfo numberOfObjects]) ;
return ([sectionInfo numberOfObjects]);
}
#pragma mark - NSFetchedResultsControllerDelegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[[self tableView] beginUpdates];
DDLogVerbose(#"In controllerWillChangeContent") ;
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
DDLogVerbose(#"In controller didChangeSection for change type %d",type) ;
switch(type) {
case NSFetchedResultsChangeInsert:
[[self tableView] insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[[self tableView] deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeMove:
case NSFetchedResultsChangeUpdate:
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type newIndexPath:(NSIndexPath *)newIndexPath
{
switch(type) {
case NSFetchedResultsChangeInsert:
[[self tableView] insertRowsAtIndexPaths:#[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
DDLogVerbose(#"In controller didChangeObject for change type NSFetchedResultsChangeInsert with row index = %ld",(long)newIndexPath.row) ;
break;
case NSFetchedResultsChangeDelete:
[[self tableView] deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
DDLogVerbose(#"In controller didChangeObject because row %ld was deleted",(long)indexPath.row) ;
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[[self tableView] cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
DDLogVerbose(#"In controller didChangeObject because row %ld was updated",(long)indexPath.row) ;
break;
case NSFetchedResultsChangeMove:
[[self tableView] deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[[self tableView] insertRowsAtIndexPaths:#[newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
DDLogVerbose(#"In controller didChangeObject because row %ld was moved to %ld",(long)indexPath.row,(long)newIndexPath.row) ;
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[[self tableView] endUpdates];
[[self tableView] beginUpdates];
DDLogVerbose(#"In controllerDidChangeContent") ;
}
#pragma mark - Handling compose button
- (void)actionCompose:(UIBarButtonItem *)sender
//-------------------------------------------------------------------------------------------------------------------------------------------------
{
MessageDisplayViewController *vc = [MessageDisplayViewController messagesViewController];
vc.hidesBottomBarWhenPushed = YES;
vc.title = #"New Tweet";
vc.recipient = #"*" ;
[self.navigationController pushViewController:vc animated:YES];
}
#end
Try Removing this line :
//[[self tableView] beginUpdates];
The beginUpdates must always be followed by a call to the endUpdates method.
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
[[self tableView] endUpdates];
//[[self tableView] beginUpdates]; <====== Remove this
DDLogVerbose(#"In controllerDidChangeContent") ;
}
As per the documentation :
Call this method if you want subsequent insertions, deletion, and selection operations (for example, cellForRowAtIndexPath: and indexPathsForVisibleRows) to be animated simultaneously. You can also use this method followed by the endUpdates method to animate the change in the row heights without reloading the cell. This group of methods must conclude with an invocation of endUpdates. These method pairs can be nested. If you do not make the insertion, deletion, and selection calls inside this block, table attributes such as row count might become invalid. You should not call reloadData within the group; if you call this method within the group, you must perform any animations yourself.
I use the following code to delete the records from my table view and from core data. But the records are only delete permanent from the table view but not from core data:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
[self.managedObjectContext deleteObject:[self.fetchedRecordsArray objectAtIndex:indexPath.row]];
NSError *error;
if (![self.managedObjectContext save:&error]) {
NSLog(#"Whoops, couldn't save: %#", [error localizedDescription]);
}
tpAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
self.fetchedRecordsArray = [appDelegate getAllRecords];
[tableView endUpdates];
}
}
In CoreData, first you have to fetch objects that has to be deleted, using NSFetchRequest and NSPredicate.
Then, you should iterate through NSManagedObject and call deleteObject.
i'm trying to delete an object in core data when you press swipe and press delete. The problem is it deletes the the tablecell, but when i go back and in again the deleted cells are back again. I guess thats because i only deleted the object in the NSMUtableArray (devices) and did not delete the core data object. How can i do this?
The saveTap where the objects are saved:
-(void)saveTap:(id)sender{
Entity *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Entity" inManagedObjectContext:_managedObjectContext];
[newManagedObject setValue:self.textfield.text forKey:#"playlistName"];
[newManagedObject setValue:[NSNumber numberWithInt:selectedRowValue] forKey:#"idnumber"];
// Save the context.
NSError *error = nil;
if (![_managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[self fetchDevices];
NSLog(#"COUNT %d", [devices count]);
}
and the commiteditingstyle method
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[self.devices removeObjectAtIndex:indexPath.row];
[tableViewData reloadData]; }
}
Is [self.devices objectAtIndex:indexPath.row]; returning that NSManagedObject you want to delete?
Then you should make the second function like this:
- (void)tableView:(UITableView *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_managedObjectContext deleteObject:[self.devices objectAtIndex:indexPath.row]];
[_managedObjectContext save:nil];
[self.devices removeObjectAtIndex:indexPath.row];
[tableViewData reloadData]; }
}
Instead of reloading while of UitableView you should only reloadrowatindexpaths: and before it [UITableView beganEditing];
And after Reloading rows
[UITableView endEditing];
I want to refresh tagListTableView.
but it doesn't refresh.
When delete button on UITableview cell is tapped , object in coraData's date could be removed.
but, Deleting a cell in a table view is still exposed to the screen to blank.
I tried to [tagListTableView reloadData] on viewWillAppear, viewDidAppear, .....more.
What am I missing??
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tableView
commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if (editingStyle == UITableViewCellEditingStyleDelete) {
Voca_Tag *tag = (Voca_Tag *)[self.fetchedResultsController objectAtIndexPath:indexPath];
UITableViewCell *cell = [tagListTableView cellForRowAtIndexPath:indexPath];
[cell setSelected:NO animated:YES];
[tag.managedObjectContext deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]]; // [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
[tagListTableView reloadData];
[pickedTags removeObject:tag];
cell.accessoryType = UITableViewCellAccessoryNone;
NSError *error = nil;
if (![tag.managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
- (BOOL)tableView:(UITableView *)tableView
canEditRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
if (editingStyle == UITableViewCellEditingStyleDelete) {
Voca_Tag *tag = (Voca_Tag *)[self.fetchedResultsController objectAtIndexPath:indexPath];
UITableViewCell *cell = [tagListTableView cellForRowAtIndexPath:indexPath];
[cell setSelected:NO animated:YES];
[tag.managedObjectContext deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]]; // [tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
//********
//REMOVE the object before reloading the table
[pickedTags removeObject:tag];
[tagListTableView reloadData];
cell.accessoryType = UITableViewCellAccessoryNone;
NSError *error = nil;
if (![tag.managedObjectContext save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
You should remove object from your pickedTags before you reload the tableview, you were doing is after reload.
It might help you.
I am building an app with use of core data. My RootViewController, loaded by the appDelegate is mostly stock from the template. However I have changed the entity name to "Clocks" and added a bunch of rows.
My RootViewController presents an MVC which has a UINavigationController. When I save data to my database the UINavigationController class saved the data using [[UIApplication sharedApplication]delegate] to access my appDelegate which actually preforms the save action.
Editing data goes the same way, but instead of calling the insert function in my app delegate, it calls the update function.
Now, all this goes fine.. perfectly actually. BUT... after a few times just opening edit and saving in the view my app crashes. It does this both in the simulator and on my iPhone 4. This is an example of what I mean (Movie): http://dl.dropbox.com/u/3077127/has_been_invalidated.mov
This is the code of my RootViewController.m:
#import "RootViewController.h"
#import "RootViewControllerClockCell.h"
#import "RootViewControllerClockCellFooter.h"
#import "configuration.h"
#import "AddClockViewController.h"
#import "clockAppDelegate.h"
#import "AddClockNavigationController.h"
#interface RootViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation RootViewController
#synthesize fetchedResultsController=fetchedResultsController_, managedObjectContext=managedObjectContext_;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
[self setTitle:NSLocalizedString(#"Alarms", #"AddClockNavigationController")];
// Set up the edit and add buttons.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showAddAlarmView)];
self.navigationItem.rightBarButtonItem = addButton;
[addButton release];
[self.tableView setSeparatorStyle:UITableViewCellSeparatorStyleNone];
[self.tableView setBackgroundColor:[UIColor clearColor]];
[self.tableView setBackgroundView:[[[UIImageView alloc] initWithImage:[UIImage imageNamed:#"clockTableBackground"]] autorelease]];
[self.tableView setAllowsSelectionDuringEditing:YES];
if (managedObjectContext_ == nil)
{
managedObjectContext_ = [(ClockAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
NSLog(#"After managedObjectContext: %#", managedObjectContext_);
}
locationManager = [[CLLocationManager alloc] init];
locationManager.delegate=self;
locationManager.desiredAccuracy=kCLLocationAccuracyBest;
[locationManager startUpdatingLocation];
}
- (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation {
location = newLocation.coordinate;
[locationManager stopUpdatingLocation];
[self.tableView reloadData];
}
- (void)viewWillDisappear:(BOOL)animated
{
[locationManager stopUpdatingLocation];
[super viewWillDisappear:animated];
}
// Implement viewWillAppear: to do additional setup before the view is presented.
- (void)viewWillAppear:(BOOL)animated {
[locationManager startUpdatingLocation];
[super viewWillAppear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
if ([Configuration isIpad])
{
return YES;
}
else {
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
// #TODO
// Remove unused function
}
- (void)showAddAlarmView
{
AddClockNavigationController *viewController = [[AddClockNavigationController alloc] initWithNibName:#"AddClockNavigationController" bundle:nil];
[[self navigationController] presentModalViewController:viewController animated:YES];
[viewController release];
}
#pragma mark -
#pragma mark Add a new object
- (void)setEditing:(BOOL)editing animated:(BOOL)animated
{
[super setEditing:(BOOL)editing animated:(BOOL)animated];
self.navigationItem.rightBarButtonItem.enabled = !editing;
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
int retValue = [sectionInfo numberOfObjects];
retValue++;
return retValue;
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:indexPath.section];
if (indexPath.row < [sectionInfo numberOfObjects])
{
static NSString *CellIdentifier = #"RootViewControllerClockCell";
RootViewControllerClockCell *cell = (RootViewControllerClockCell*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"RootViewControllerClockCell" owner:nil options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[RootViewControllerClockCell class]])
{
cell = (RootViewControllerClockCell *)currentObject;
break;
}
}
}
// Configure the cell.
NSManagedObject *managedObject = [[self.fetchedResultsController objectAtIndexPath:indexPath] retain];
[[cell titleText] setText:[[managedObject valueForKey:#"title"] description]];
UISwitch *mySwitch = [[[UISwitch alloc] initWithFrame:CGRectZero] autorelease];
[cell addSubview:mySwitch];
cell.accessoryView = mySwitch;
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
[mySwitch setTag:indexPath.row];
BOOL isOn = [(NSNumber*)[managedObject valueForKey:#"active"] boolValue];
[(UISwitch *)cell.accessoryView setOn:isOn];
[(UISwitch *)cell.accessoryView addTarget:self action:#selector(setClockEnabled:) forControlEvents:UIControlEventValueChanged];
[cell setEditingAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
[currentLocation release];
[cellLocation release];
[managedObject release];
return cell;
}
else {
static NSString *CellIdentifier = #"RootViewControllerClockCellFooter";
RootViewControllerClockCellFooter *cell = (RootViewControllerClockCellFooter*)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil){
NSArray *topLevelObjects = [[NSBundle mainBundle] loadNibNamed:#"RootViewControllerClockCellFooter" owner:nil options:nil];
for(id currentObject in topLevelObjects)
{
if([currentObject isKindOfClass:[RootViewControllerClockCellFooter class]])
{
cell = (RootViewControllerClockCellFooter *)currentObject;
break;
}
}
}
return cell;
}
}
- (NSString*)distanceToString:(double)distance
{
NSString *returnString = #"";
if (distance < 1000)
{
returnString = [NSString stringWithFormat:#"%gm", round(distance)];
}
else {
returnString = [NSString stringWithFormat:#"%gkm", round(distance/1000)];
}
return returnString;
}
- (void)setClockEnabled:(UISwitch*)sender
{
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:sender.tag inSection:0];
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
[managedObject setValue:[NSNumber numberWithBool:sender.on] forKey:#"active"];
NSError *error = nil;
if (![fetchedResultsController_ performFetch:&error]) {
/*
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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:indexPath.section];
if ((indexPath.row > [sectionInfo numberOfObjects]-1) || [self.tableView numberOfRowsInSection:indexPath.section] == 1)
return NO;
else
return YES;
}
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
// Delete the managed object for the given index path
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:[self.fetchedResultsController objectAtIndexPath:indexPath]];
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
/*
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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
if ([self.tableView numberOfRowsInSection:0] == 1)
{
[self.tableView reloadData];
}
}
}
- (void)updateAlarm:(NSManagedObject*)originalAlarm withAlarm:(NSManagedObject*)newAlarm
{
NSLog(#"Update!");
NSManagedObjectContext *context = [self.fetchedResultsController managedObjectContext];
[context deleteObject:originalAlarm];
[context insertObject:newAlarm];
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
/*
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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath {
// The table view should not be re-orderable.
return NO;
}
#pragma mark -
#pragma mark Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
NSLog(#"Did select row");
if ([self.tableView isEditing])
{
// Show editing mode
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
AddClockNavigationController *viewController = [[AddClockNavigationController alloc] initWithNibName:#"AddClockNavigationController" bundle:nil editManagedObject:managedObject];
[[self navigationController] presentModalViewController:viewController animated:YES];
[viewController release];
}
}
- (void)cancelAddAlarmView
{
[self.modalViewController dismissModalViewControllerAnimated:YES];
}
#pragma mark -
#pragma mark Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController {
if (fetchedResultsController_ != nil) {
return fetchedResultsController_;
}
/*
Set up the fetched results controller.
*/
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Clocks" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"addDate" ascending:NO];
NSArray *sortDescriptors = [[NSArray alloc] initWithObjects:sortDescriptor, nil];
[fetchRequest setSortDescriptors:sortDescriptors];
// Edit the section name key path and cache name if appropriate.
// nil for section name key path means "no sections".
NSFetchedResultsController *aFetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil cacheName:#"Root"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![fetchedResultsController_ performFetch:&error]) {
/*
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. If it is not possible to recover from the error, display an alert panel that instructs the user to quit the application by pressing the Home button.
*/
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
return fetchedResultsController_;
}
#pragma mark -
#pragma mark Fetched results controller delegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller {
[self.tableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type {
switch(type) {
case NSFetchedResultsChangeInsert:
[self.tableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.tableView deleteSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controller:(NSFetchedResultsController *)controller didChangeObject:(id)anObject
atIndexPath:(NSIndexPath *)indexPath forChangeType:(NSFetchedResultsChangeType)type
newIndexPath:(NSIndexPath *)newIndexPath {
UITableView *tableView = self.tableView;
switch(type) {
case NSFetchedResultsChangeInsert:
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeUpdate:
[self configureCell:[tableView cellForRowAtIndexPath:indexPath] atIndexPath:indexPath];
break;
case NSFetchedResultsChangeMove:
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
[tableView insertRowsAtIndexPaths:[NSArray arrayWithObject:newIndexPath]withRowAnimation:UITableViewRowAnimationFade];
break;
}
}
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
[self.tableView endUpdates];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:indexPath.section];
if (indexPath.row < [sectionInfo numberOfObjects])
{
return 92;
}
else {
return 40;
}
}
/*
// Implementing the above methods to update the table view in response to individual changes may have performance implications if a large number of changes are made simultaneously. If this proves to be an issue, you can instead just implement controllerDidChangeContent: which notifies the delegate that all section and object changes have been processed.
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller {
// In the simplest, most efficient, case, reload the table view.
[self.tableView reloadData];
}
*/
#pragma mark -
#pragma mark Memory management
- (void)didReceiveMemoryWarning {
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Relinquish ownership any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload {
// Relinquish ownership of anything that can be recreated in viewDidLoad or on demand.
// For example: self.myOutlet = nil;
}
- (void)dealloc {
[fetchedResultsController_ release];
[managedObjectContext_ release];
[locationManager stopUpdatingLocation];
[locationManager release];
[super dealloc];
}
#end
EDIT
This is the code of the save button, AddClockNavigationController.m:
- (IBAction)saveAlarm
{
[self saveTheAlarm];
}
- (void)saveTheAlarm
{
AddClockViewController *viewController = [navigationController.viewControllers objectAtIndex:0];
UITableView *alarmTable = viewController.theTable;
NSIndexPath *textFieldIndexPath = [NSIndexPath indexPathForRow:0 inSection:0];
UITextField *textField = (UITextField*)[[alarmTable cellForRowAtIndexPath:textFieldIndexPath] accessoryView];
ClockAppDelegate *appDelegate = (ClockAppDelegate*)[[UIApplication sharedApplication] delegate];
RootViewController *parentView = [[RootViewController alloc] init];
[appDelegate addNewAlarmWithTitle:textField.text sound:#"" recurring:[viewController hasRecurring] recurringDays:viewController.recurringDictionary];
[parentView.tableView reloadData];
[self.parentViewController dismissModalViewControllerAnimated:YES];
[parentView release];
}
ClockAppDelegate.m
- (void)addNewAlarmWithTitle:(NSString*)alarmTitle sound:(NSString*)sound recurring:(BOOL)isRecurring recurringDays:(NSDictionary*)days
{
NSManagedObjectContext *context = managedObjectContext_;
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Clocks" inManagedObjectContext:context];
[newManagedObject setValue:alarmTitle forKey:#"title"];
[newManagedObject setValue:sound forKey:#"alarm"];
[newManagedObject setValue:[NSNumber numberWithBool:TRUE] forKey:#"active"];
[newManagedObject setValue:[[NSDate alloc] init] forKey:#"addDate"];
[newManagedObject setPrimitiveValue:[NSNumber numberWithBool:isRecurring] forKey:#"recurring"];
NSArray *myKeys = [days allKeys];
NSArray *sortedKeys = [myKeys sortedArrayUsingSelector:#selector(caseInsensitiveCompare:)];
for (id key in sortedKeys) {
if ([(NSString*)[days objectForKey:key] isEqualToString:#"1"])
{
if ([key isEqualToString:#"0"])
{
[newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:#"mon"];
}
else if ([key isEqualToString:#"1"])
{
[newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:#"tue"];
}
else if ([key isEqualToString:#"2"])
{
[newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:#"wed"];
}
else if ([key isEqualToString:#"3"])
{
[newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:#"thu"];
}
else if ([key isEqualToString:#"4"])
{
[newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:#"fri"];
}
else if ([key isEqualToString:#"5"])
{
[newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:#"sat"];
}
else if ([key isEqualToString:#"6"])
{
[newManagedObject setPrimitiveValue:[NSNumber numberWithBool:TRUE] forKey:#"sun"];
}
}
}
// Save the context.
NSError *error = nil;
if (![context save:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
What is it I am doing wrong?
Best regards,
Paul Peelen
From Core Data Docs
Managed object invalidated Problem:
You see an exception that looks
similar to this example:
[_assignObject:toPersistentStore:]:
The NSManagedObject with ID:#### has
been invalidated. Cause: Either you
have removed the store for the fault
you are attempting to fire, or the
managed object's context has been sent
a reset message.
Remedy: You should discard this
object. If you add the store again,
you can try to fetch the object again
So, basically, you have a reference to managed object that has become disconnected from its store or context.
I don't see an obviousl place for this to happen but you are sending a retain message to a managed object in tableView:cellForRowAtIndexPath: here:
NSManagedObject *managedObject = [[self.fetchedResultsController objectAtIndexPath:indexPath] retain];
... which is dangerous even if you subsequently release it. Never retain managed objects but instead rely on the context to retain it. Otherwise, the context may release the managed object and mark it as invalidated while another object keeps it alive.
I would suggest going through all your code and finding all places you send a retain to a managed object and remove the unnecessary retain/release code. That will probably resolve the problem.
If not you need to check that your persistent store is and remains properly assigned to the persistent store coordinator.
I have faced this problem and i have soloed by comment RESET for managed object context below description for this problem from apple documentation :
You can use the reset method of NSManagedObjectContext to remove all managed objects associated with a context and "start over" as if you'd just created it. Note that any managed object associated with that context will be invalidated, and so you will need to discard any references to and re-fetch any objects associated with that context in which you are still interested.