Issue with overlapping images in UITableView cells - objective-c

I have 2 tables in coredata sqlite Painter and Picture. With relationship one-to-many.
In table "picture" I have string attribute pictureName. I store pictures(153) on a disk
This code I add imageViews to cells:
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error]) {
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
self.tableView.transform = CGAffineTransformMakeRotation( -M_PI/2 );
self.tableView.showsHorizontalScrollIndicator = NO;
self.tableView.showsVerticalScrollIndicator = NO;
[self.tableView setFrame:CGRectMake(0, 156, 1024, 449)];
}
- (void)viewDidUnload
{
[self setTableView:nil];
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return YES;
}
#pragma mark - UITableView Delegate Methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[fetchedResultsController fetchedObjects] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
Painter *painter = [[fetchedResultsController fetchedObjects] objectAtIndex:section];
//NSLog(#"%i", [painter.pictures count]);
return [painter.pictures count];
//return 152;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
Painter *painter = [[fetchedResultsController fetchedObjects] objectAtIndex:indexPath.section];
Picture *picture = [[painter.pictures allObjects] objectAtIndex:indexPath.row];
UIImageView *imageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:[NSString stringWithFormat:#"%#s.jpg", picture.imgName]]];
NSLog(#"add image %#s.jpg to sector:%i row:%i", picture.imgName, indexPath.section, indexPath.row);
imageView.transform = CGAffineTransformMakeRotation( M_PI/2 );
[cell addSubview:imageView];
[imageView release];
}
- (UITableViewCell *)tableView:(UITableView *)tableViewCurrent cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableViewCurrent dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (CGFloat)tableView:(UITableView *)aTableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
return 300.0;
}
- (void)tableView:(UITableView *)aTableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController != nil) {
return fetchedResultsController;
}
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Painter" inManagedObjectContext: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:#"name" 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:managedObjectContext sectionNameKeyPath:nil cacheName:#"Main"];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
return fetchedResultsController;
}
`
And I have problem: a lot of photo in every cell
http://ge.tt/9QX5lc4?c
(select view button)
Why?

Cells are being reused. Every time you are configuring a cell, you are adding an image view as a subview. Over time these accumulate and are providing the effect you are seeing. You should check if an image view already exists and assign an image to it or clean up the cell first and then set it up with an image.

The following code is what is causing the problem for you:
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableViewCurrent dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;
You're basically caching the cell the first time it's created and re-using it on subsequent calls to tableView:cellForRowAtIndexPath: If you don't want this to be cached then you'll need to create a new cell every time.
UITableViewCell *cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;
This should fix your issue. There are more elaborate ways of handling cells such as caching it and manipulating its subviews directly instead of recreating it every time. Something to keep in mind as you continue to work on your code.

Related

UITableViewController application crashes

The UITableViewController freezes when scrolling or when viewDidAppear:. I see that when the problem starts, the app start to allocate objects uncontrollably.
I have the following project for iOS: basically download information from CoreData, but when I go to display the data in the table, the application freezes (both the device and the simulator). But if I show the arrangement in a downloaded NSLog no errors. The code is as follows:
I see that when the problem starts, the app start to allocate objects uncontrollably.
The UITableViewController freezes when scrolling or when viewDidAppear:
TableViewController.h
#interface Set_ScheduleViewController : UITableViewController
{
STCore *core;
UILabel *label;
NSArray *objects;
}
#end
TableViewController.m:
#implementation Set_ScheduleViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
core = [[STCore alloc] init];
[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;
}
- (void)reloadData
{
NSSortDescriptor *sort = [[NSSortDescriptor alloc] initWithKey:#"name" ascending:YES];
objects = [core getAllClassesUsingSortDescriptions:#[sort]];
[[self tableView] reloadData];
}
- (void)viewDidAppear:(BOOL)animated
{
[self reloadData];
[super viewDidAppear:animated];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
// Return the number of rows in the section.
return [objects count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 120, 20)];
label.textColor = [UIColor colorWithHex:0x88B6DB];
label.font = [UIFont systemFontOfSize:12.0f];
label.backgroundColor = [UIColor clearColor];
label.textAlignment = UITextAlignmentRight;
label.minimumFontSize = 12.0f;
tableView.separatorColor = [UIColor colorWithHex:0xDAE1E6];
cell.textLabel.backgroundColor = [UIColor clearColor];
cell.textLabel.textColor = [UIColor colorWithHex:0x393B40];
cell.textLabel.font = [UIFont boldSystemFontOfSize:16.0f];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
cell.detailTextLabel.textColor = [UIColor colorWithHex:0x393B40];
cell.detailTextLabel.font = [UIFont systemFontOfSize:12.0f];
}
cell.textLabel.text = [[objects objectAtIndex:indexPath.row] name];
cell.detailTextLabel.text = [[objects objectAtIndex:indexPath.row] location];
STMultipleDate *dates = [STMultipleDate new];
for (Schedule *sch in [[objects objectAtIndex:indexPath.row] schedule]) {
STDate *date = [STDate new];
[date setWeekday:[[sch day] integerValue]];
[date setHour:[[sch hour] integerValue]];
[date setMinutes:[[sch minutes] integerValue]];
[dates addDate:date];
}
label.text = [STCore splitDates:dates];
cell.accessoryView = label;
return cell;
}
- (NSString *)tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
{
if ([objects count] < 1) {
return NSLocalizedString(#"SETSCH_FOOTER_DEFAULT_404", #"");
}
return nil;
}
STCore.m
- (NSArray *)getAllClassesUsingSortDescriptions:(NSArray *)descs
{
if (![self isReady]) {
return #[];
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Classes" inManagedObjectContext:_context];
[fetchRequest setEntity:entity];
[fetchRequest setSortDescriptors:descs];
NSError *error;
NSArray *returned = [_context executeFetchRequest:fetchRequest error:&error];
if (error) {
[_delegate core:self didRecivedAnError:error];
}
return returned;
}
In your viewDidLoad you're locking the context with [[core context] lock];, which is causing your getAllClassesUsingSortDescriptions to wait for the lock to clear. Remove the lock.

Objective-C, iOS SDK, NSMutableArray, add elements and save data

Basically, every time I enter something in my textfield and save it to the table, the previous entry will be replaced by the new one. How do I add elements in a mutable array and save the last entry? I tried
[tabledata addObject....
and in the entry
tabledata.lastObject objectAtIndex...
but that didn't work.
here is what I have:
-(void)viewDidLoad
{
[super viewDidLoad];
titlestring = [[NSUserDefaults standardUserDefaults] objectForKey:#"titlehomework" ];
detailsstring = [[NSUserDefaults standardUserDefaults] objectForKey:#"detailshomework"];
tabledata = [[NSMutableArray alloc] initWithObjects:titlestring, nil];
tablesubtitles = [[NSMutableArray alloc] initWithObjects:detailsstring, nil];
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section;
{
return [tabledata count];
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath;
{
UITableViewCell *cell = nil;
cell = [tableView dequeueReusableCellWithIdentifier:#"homeworkcell"];
if(cell == nil)
{
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"homeworkcell"];
}
cell.textLabel.text = [tabledata objectAtIndex:indexPath.row];
cell.detailTextLabel.text = [tablesubtitles objectAtIndex:indexPath.row];
cell.textLabel.font = [UIFont systemFontOfSize:14.0];
cell.textLabel.backgroundColor = [ UIColor clearColor ];
cell.detailTextLabel.backgroundColor = [UIColor clearColor];
//-----------------------------------------START----------------------------Set image of cell----
cellImage = [UIImage imageNamed:#"checkboxblank.png"];
cell.imageView.image = cellImage;
//--------------------------------------------END---------------------------end set image of cell--
return cell;
}
Without seeing more code, the best I can do is suggest something like this
[tabledata addObject:newTitle];
[tablesubtitles addObject:newSubtitle];
[tableView reloadData];
This assumes both newTitle and newSubtitle are the NSStrings you wish to add and that tableView is the pointer to the UITableView.

Pushing data from one View to another

I have a table list of promotions held in an NSSet which I load into an array for the purpose of displaying the title/name on the cell. However I want to use the didselectrow method to push the selected promotion onto an individual promotion page. I've making promo.featuredArray = self.featuredArray however it doesn't seem to be passing the data. My code is as follows.
Promo list.m
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
NSString *CellIdentifier = #"CellIdentifier";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
Featured*featured = [self.featuredArray objectAtIndex:indexPath.row];
cell.textLabel.text = featured.details;
cell.textLabel.textColor = [UIColor whiteColor];
cell.detailTextLabel.text = self.place.name;
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
Promo * promo= [[Promo alloc] initWithNibName:#"Promo" bundle:nil];
//Featured*featured = [self.featuredArray objectAtIndex:indexPath.row];
promo.featuredArray = self.featuredArray;
[self.navigationController pushViewController:promo animated:YES];
[promo release];
//[featured release];
}
Promo.m
#synthesize featuredArray, featured = __featured;
- (void)viewDidLoad
{
self.clearImage = [UIImage imageNamed:#"fav_icon.png"];
self.clearImagePressed = [UIImage imageNamed:#"fav_icon_sel.png"];
Featured*featured = [self.featuredArray init];
self.name.text = [NSString stringWithFormat:#"%#", __featured.name];
self.time.text = [NSString stringWithFormat:#"%#", __featured.time];
// self.description.text = [NSString stringWithFormat:#"%#", __featured.description];
self.placeName.text = [NSString stringWithFormat:#"%#", __featured.Place];
[super viewDidLoad];
if([__featured.imageURL hasPrefix:#"http"])
{
[self getImageForPlace];
}
// else
// {
// [self refreshImage];
// }
//
self.title = #"Promotion";
UIColor *background = [[UIColor alloc] initWithPatternImage:[UIImage imageNamed:#"background_texture.png"]];
self.view.backgroundColor = background;
[background release];
[featured release];
}
It's probably this line:
Featured*featured = [self.featuredArray init];
This is wrong in many ways.
Making this a community wiki because I don't have time to write a full answer.

Getting a crash relating to deallocated instance

I am getting a crash at line [selectedSession release]; in dealloc:
Default [NSCheapMutableString release]: message sent to deallocated instance
I don't understand why isn't this normal to put in dealloc?
All current code below:
LogViewController
#implementation LogViewController
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext;
#synthesize logArray;
#synthesize logTableView;
#synthesize imageView;
#synthesize session;
#synthesize selectedSession;
- (void)dealloc
{
[logArray release];
[logTableView release];
[session release];
[__fetchedResultsController release];
[managedObjectContext release];
[imageView release];
[selectedSession release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
self.logTableView.rowHeight = 47;
[super viewDidLoad];
self.navigationItem.title = #"Log";
logTableView.backgroundColor = [UIColor clearColor];
logTableView.separatorColor = [UIColor grayColor];
self.navigationController.navigationBar.tintColor = [UIColor colorWithRed:24/255.0 green:83/255.0 blue:170/255.0 alpha:1.0];
self.logArray = [[NSArray alloc]initWithObjects:#"Today", #"Previous", #"Past Week", #"Past Month", #"All Workouts", nil];
if (managedObjectContext == nil)
{
self.managedObjectContext = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] managedObjectContext];
}
}
- (void)viewDidUnload
{
self.logTableView = nil;
self.fetchedResultsController = nil;
self.imageView = nil;
self.managedObjectContext = nil;
[super viewDidUnload];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
}
- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];
}
- (void)viewDidDisappear:(BOOL)animated
{
[super viewDidDisappear:animated];
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [self.logArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
TDBadgedCell *cell = [[[TDBadgedCell alloc] initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:CellIdentifier] autorelease];
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(TDBadgedCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
cell.textLabel.textColor = [UIColor blackColor];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.textLabel.text = [logArray objectAtIndex:indexPath.row];
cell.backgroundColor = [UIColor clearColor];
cell.imageView.image = [UIImage imageNamed:#"17-bar-chart.png"];
UIImageView *myImageView = nil;
myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"silvercell5.png"]];
[cell setBackgroundView:myImageView];
[myImageView release];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSDate *date = nil;
if (indexPath.row == 0)
{
date = [NSDate date];
NSString *dateString = [dateFormatter stringFromDate:date];
cell.badgeString = dateString;
}
else if (indexPath.row == 1)
{
if ([[self.fetchedResultsController fetchedObjects]count] > 1)
{
self.session = [[self.fetchedResultsController fetchedObjects]objectAtIndex:1];
NSDate *date = self.session.timeStamp;
NSString *dateString = [dateFormatter stringFromDate:date];
cell.badgeString = dateString;
}
else
{
cell.badgeString = #"None";
}
}
else if (indexPath.row > 1)
{
cell.badgeString = [NSString stringWithFormat:#"%i", [[self.fetchedResultsController fetchedObjects]count]];
}
cell.badgeColor = [UIColor colorWithRed:24/255.0 green:83/255.0 blue:170/255.0 alpha:1.0];
[dateFormatter release];
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
if (indexPath.row == 0 || indexPath.row == 1)
{
SessionViewController *detailViewController = [[SessionViewController alloc] initWithNibName:#"SessionViewController" bundle:nil];
detailViewController.title = [logArray objectAtIndex: indexPath.row];
self.selectedSession = (Session *)[__fetchedResultsController objectAtIndexPath:indexPath];
detailViewController.selectedSession = self.selectedSession;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:selectedSession.timeStamp];
detailViewController.title = dateString;
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
[dateFormatter release];
}
else
{
LogResultsViewController *detailViewController = [[LogResultsViewController alloc] initWithNibName:#"LogResultsTableViewController" bundle:nil];
detailViewController.title = [logArray objectAtIndex: indexPath.row];
[self.navigationController pushViewController:detailViewController animated:YES];
[detailViewController release];
}
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController != nil)
{
return fetchedResultsController;
}
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0] ;
NSDate *today = [NSDate date];
NSDate *thisWeek = [today dateByAddingTimeInterval: -604800.0];
NSDate *thisMonth = [today dateByAddingTimeInterval: -2629743.83]; // Use NSCalendar for
if (indexPath.row ==2)
{
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"(date >= %#) AND (date <= %#)", thisWeek, today]];
}
else if (indexPath.row ==3)
{
[fetchRequest setPredicate:[NSPredicate predicateWithFormat:#"(date >= %#) AND (date <= %#)", thisMonth, today]];
}
// Set the batch size to a suitable number.
[fetchRequest setFetchBatchSize:20];
// Edit the sort key as appropriate.
NSSortDescriptor *sortDescriptor = [[NSSortDescriptor alloc] initWithKey:#"timeStamp" 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:nil];
aFetchedResultsController.delegate = self;
self.fetchedResultsController = aFetchedResultsController;
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
NSError *error = nil;
if (![self.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();
}
NSLog(#"Number of Objects = %i",
[[fetchedResultsController fetchedObjects] count]);
return fetchedResultsController;
NSLog(#"Number of Objects = %i",
[[fetchedResultsController fetchedObjects] count]);
}
#pragma mark - Fetched results controller delegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.logTableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.logTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.logTableView 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.logTableView;
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.logTableView endUpdates];
}
LogResultsViewController
#implementation LogResultsViewController
#synthesize fetchedResultsController = __fetchedResultsController;
#synthesize managedObjectContext;
#synthesize resultsTableView;
#synthesize selectedSession;
- (void)dealloc
{
[__fetchedResultsController release];
[managedObjectContext release];
[selectedSession release];
[resultsTableView release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
self.resultsTableView.separatorColor = [UIColor grayColor];
self.resultsTableView.rowHeight = 50;
[self managedObjectContext];
}
- (NSManagedObjectContext *)managedObjectContext
{
if (managedObjectContext != nil)
{
return managedObjectContext;
}
NSPersistentStoreCoordinator *coordinator = [(CurlAppDelegate *)[[UIApplication sharedApplication] delegate] persistentStoreCoordinator];
if (coordinator != nil)
{
managedObjectContext = [[NSManagedObjectContext alloc] init];
[managedObjectContext setPersistentStoreCoordinator:coordinator];
}
return managedObjectContext;
}
- (void)viewDidUnload
{
[super viewDidUnload];
self.managedObjectContext = nil;
self.fetchedResultsController = nil;
self.resultsTableView = nil;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier] autorelease];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
Session *session = (Session *)[__fetchedResultsController objectAtIndexPath:indexPath];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"eeee, MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:session.timeStamp];
NSDate *lastDate = session.timeStamp;
NSDate *todaysDate = [NSDate date];
NSTimeInterval lastDiff = [lastDate timeIntervalSinceNow];
NSTimeInterval todaysDiff = [todaysDate timeIntervalSinceNow];
NSTimeInterval dateDiff = todaysDiff-lastDiff;
NSTimeInterval dayDifference = dateDiff/86400;
int days = (int) dayDifference;
NSLog(#"%i days",days);
cell.textLabel.text = dateString;
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
cell.detailTextLabel.text = [NSString stringWithFormat: #"%i days ago", days];
cell.detailTextLabel.textColor = [UIColor colorWithRed:24/255.0 green:83/255.0 blue:170/255.0 alpha:1.0];
cell.imageView.image = [UIImage imageNamed:#"11-clock.png"];
self.resultsTableView.tableFooterView = [[[UIView alloc] init] autorelease];
UIImageView *myImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:#"silvercell3.png"]];
[cell setBackgroundView:myImageView];
[dateFormatter release];
[myImageView release];
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
// Delete the managed object for the given index path
NSManagedObjectContext *context = [__fetchedResultsController managedObjectContext];
[context deleteObject:[__fetchedResultsController objectAtIndexPath:indexPath]];
// Commit the change.
NSError *error = nil;
// Update the array and table view.
if (![managedObjectContext save:&error])
{
// Handle the error.
}
//[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:YES];
}
}
// Override to support conditional editing of the table view.
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
SessionViewController *sessionViewController = [[SessionViewController alloc] initWithNibName:#"SessionViewController" bundle:nil];
selectedSession = (Session *)[__fetchedResultsController objectAtIndexPath:indexPath];
sessionViewController.selectedSession = self.selectedSession;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:#"MMM d, y"];
NSString *dateString = [dateFormatter stringFromDate:selectedSession.timeStamp];
sessionViewController.title = dateString;
[self.navigationController pushViewController:sessionViewController animated:YES];
[sessionViewController release];
[dateFormatter release];
}
#pragma mark - Fetched results controller
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController != nil)
{
return fetchedResultsController;
}
// Create the fetch request for the entity.
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Edit the entity name as appropriate.
NSEntityDescription *entity = [NSEntityDescription entityForName:#"Session" 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:#"timeStamp" 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:nil];
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 - Fetched results controller delegate
- (void)controllerWillChangeContent:(NSFetchedResultsController *)controller
{
[self.resultsTableView beginUpdates];
}
- (void)controller:(NSFetchedResultsController *)controller didChangeSection:(id <NSFetchedResultsSectionInfo>)sectionInfo
atIndex:(NSUInteger)sectionIndex forChangeType:(NSFetchedResultsChangeType)type
{
switch(type)
{
case NSFetchedResultsChangeInsert:
[self.resultsTableView insertSections:[NSIndexSet indexSetWithIndex:sectionIndex] withRowAnimation:UITableViewRowAnimationFade];
break;
case NSFetchedResultsChangeDelete:
[self.resultsTableView 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.resultsTableView;
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.resultsTableView endUpdates];
}
SessionViewController
#implementation SessionViewController
#synthesize exerciseArray;
#synthesize selectedSession;
- (void)dealloc
{
[exerciseArray release];
[selectedSession release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
-(IBAction)showActionSheet {
UIActionSheet *actionSheet = [[UIActionSheet alloc] initWithTitle:#"Share" delegate:self cancelButtonTitle:#"Cancel" destructiveButtonTitle:nil otherButtonTitles:#"Twitter",#"Facebook",nil];
[actionSheet showInView:self.tabBarController.view];
[actionSheet release];
}
- (void)tweet
{
SHKItem *aTweet = [SHKItem text:[NSString stringWithFormat: #"Twitter: testing 1,2,3."]];
[SHKTwitter shareItem:aTweet];
}
- (void)facebook
{
SHKItem *post = [SHKItem text: [NSString stringWithFormat: #"Facebook: testing 1,2,3."]];
// post.URL = [NSURL URLWithString:#"http://sugarrush-app.com/"];
[SHKFacebook shareItem:post];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
[super viewDidLoad];
UIBarButtonItem *actionButton = [[UIBarButtonItem alloc] initWithTitle:#"Share" style:UIBarButtonItemStylePlain target:self action:#selector(showActionSheet)];
self.navigationItem.rightBarButtonItem = actionButton;
[actionButton release];
NSSet *exercises = [self.selectedSession valueForKey:#"exercises"];
NSArray *sortDescriptors = [NSArray arrayWithObject:[NSSortDescriptor sortDescriptorWithKey:#"timeStamp" ascending:YES]];
NSArray *sorted = [exercises sortedArrayUsingDescriptors:sortDescriptors];
self.exerciseArray = sorted;
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [exerciseArray count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
Exercise *exercise = (Exercise *)[exerciseArray objectAtIndex:indexPath.row];
cell.textLabel.text = exercise.name;
return cell;
}
#end
The only objects you should be releasing or setting to nil in viewDidUnload are like buttons, labels, textBoxes etc.
When you do self.selectedSession = nil, for example, it is calling the release for that method; that is the point of properties, they handle the allocs and releases.
You posted a tableView:didSelectRowAtIndexPath:, but I don't think you told us which class that was in.
In any case, that method seems to have a bug:
selectedSession = (Session *)[__fetchedResultsController objectAtIndexPath:indexPath];
sessionViewController.selectedSession = self.selectedSession;
I think on the first line, you meant to say self.selectedSession, assuming you go on to release selectedSession in this class' dealloc. (This may not be your only issue)
EDIT:
You should set properties to nil in viewDidUnload if and only if those properties were set as a result of the loading of the view from your nib, or were set in loadView, or in viewDidLoad. The reason you're doing this is because viewDidLoad or loadView may be called more than once during the lifetime of the view controller.
EDIT:
Check that you are using the property when setting fetchedResultsController and make sure you aren't setting that to nil on viewDidUnload.
Dont set selectedSession and exerciseArray to nil in viewDidUnload.
Since you're doing that, it will crash in the dealloc as you're trying to release nil objects.
Also, before you release arrays, it's always a good idea to call [array removeAllObjects].
in your viewDidLoad method you are setting self.selectedSession and self.exerciseArray to nil. You should only set interface outlets to nil in viewDidLoad. But this isn't the cause of your crash because by the time you get to dealloc, you are just sending release to nil.
you might want to look into the contents of the selectedSession Object. you might be over releasing an NSString in one of it's members

managedObjectContext save issue

Over the last few days, I've searched far and wide and followed every resolution I could find online with no success.
Basically, I'm refreshing a Core Data entity from JSON data I pull from the web. I can clear out the previous data pulled from the web and load in the new data. The problem occurs when I attempt to save to Core Data "[self.managedObjectContext save:&error];".
The app just locks up.
The code from my view controller is shown below. I would greatly appreciate any assistance.
** CODE ***
//
// ChargeEntryViewController.m
// pcc
//
// Created by Tim Black on 3/14/11.
// Copyright 2011 Mobile Intents. All rights reserved.
//
#import "ChargeEntryViewController.h"
#import "pccAppDelegate.h"
#import "ChargeEntryPatientViewController.h"
#import "CJSONDeserializer.h"
#interface ChargeEntryViewController (PrivateMethods)
- (NSString *)jsonFromURLString:(NSString *)urlString;
- (void)handleError:(NSError *)error;
#end
#implementation ChargeEntryViewController
#synthesize fetchedResultsController=fetchedResultsController_;
#synthesize managedObjectContext=managedObjectContext_;
#synthesize providerArray;
#synthesize clearBtn;
#synthesize setBtn;
#synthesize patientController;
#pragma mark - Button methods
-(IBAction) clearAll:(id)sender{
selRow = -1;
[providerList reloadData];
}
-(IBAction) setPatientView:(id)sender {
if (self.patientController == nil) {
ChargeEntryPatientViewController *tmpController = [[ChargeEntryPatientViewController alloc] initWithNibName:#"ChargeEntryPatientView" bundle:nil];
self.patientController = tmpController;
[tmpController release];
}
patientController.title = #"Patient Selection";
[self.navigationController pushViewController:patientController animated:YES];
}
/*
Used to refresh the providers list from nrhsportal
*/
-(void)refreshProviders {
NSError *error = nil;
// get provider code from app delegate
pccAppDelegate *appDelegate = (pccAppDelegate *)[[UIApplication sharedApplication] delegate];
// first, clear out current list stored locally
NSFetchRequest *fetch = [[[NSFetchRequest alloc] init] autorelease];
[fetch setEntity:[NSEntityDescription entityForName:#"Provider" inManagedObjectContext:self.managedObjectContext]];
NSArray *result = [self.managedObjectContext executeFetchRequest:fetch error:&error];
if (error != nil) {
[self handleError:error];
return;
}
for (id basket in result) {
[self.managedObjectContext deleteObject:basket];
}
// add (My Patients) entry
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Provider" inManagedObjectContext:self.managedObjectContext];
[newManagedObject setValue:#"(My Patients)" forKey:#"fullname"];
[self.managedObjectContext insertObject:newManagedObject];
NSString *code = appDelegate.groupCode;
// create remote source URI
NSString *urlString = [NSString stringWithFormat:#"%s%#%s", "https://nrhsportal.nrh-ok.com/pccdata.svc/GetProviders?groupcode='", code, "'&$format=json"];
NSLog(#"URL String %#", urlString);
// Perform HTTP GET to the REST web service which returns JSON
NSString *jsonString = [self jsonFromURLString:urlString];
NSData *jsonData = [jsonString dataUsingEncoding:NSUTF32BigEndianStringEncoding];
// Parse JSON results to convert to a dictionary
CJSONDeserializer *jsonDeserializer = [CJSONDeserializer deserializer];
error = nil;
NSDictionary *resultsDictionary = [jsonDeserializer deserializeAsDictionary:jsonData error:&error];
if (error != nil) {
[self handleError:error];
return;
}
// Traverse through returned dictionary to populate tweets model
NSDictionary *topArray = [resultsDictionary objectForKey:#"d"];
NSArray *resultsArray = [topArray objectForKey:#"results"];
for (NSDictionary *resultDictionary in resultsArray) {
// create the
NSManagedObject *newManagedObject = [NSEntityDescription insertNewObjectForEntityForName:#"Provider" inManagedObjectContext:self.managedObjectContext];
NSString *providerName = [resultDictionary objectForKey:#"fullname"];
[newManagedObject setValue:providerName forKey:#"fullname"];
[self.managedObjectContext insertObject:newManagedObject];
}
error = nil;
[self.managedObjectContext save:&error];
if (error != nil) {
[self handleError:error];
return;
}
[newManagedObject release];
[result release];
}
// This will issue a request to a web service API via HTTP GET to the URL specified by urlString.
// It will return the JSON string returned from the HTTP GET.
- (NSString *)jsonFromURLString:(NSString *)urlString {
NSURL *url = [NSURL URLWithString:urlString];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:url];
[request setHTTPMethod:#"GET"];
NSURLResponse *response = nil;
NSError *error = nil;
NSData *result = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
[request release];
[self handleError:error];
NSString *resultString = [[NSString alloc] initWithData:result encoding:NSUTF8StringEncoding];
return [resultString autorelease];
}
// This shows the error to the user in an alert.
- (void)handleError:(NSError *)error {
if (error != nil) {
UIAlertView *errorAlertView = [[UIAlertView alloc] initWithTitle:#"Error" message:[error localizedDescription] delegate:nil cancelButtonTitle:#"Close" otherButtonTitles:nil];
[errorAlertView show];
[errorAlertView release];
}
}
#pragma mark - View lifecycle
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
selRow = -1;
// refresh the provider list from remote data
[self refreshProviders];
NSError *error = nil;
if (![[self 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();
}
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
NSManagedObject *managedObject = [self.fetchedResultsController objectAtIndexPath:indexPath];
cell.textLabel.text = [[managedObject valueForKey:#"fullname"] description];
cell.textLabel.font=[UIFont systemFontOfSize:16.0];
if ([cell.textLabel.text isEqualToString: #"(My Patients)"]) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
}
else {
cell.accessoryType = UITableViewCellAccessoryNone;
}
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
// Return YES for supported orientations
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#pragma mark Table view methods
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return [[self.fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
id <NSFetchedResultsSectionInfo> sectionInfo = [[self.fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
// Customize the appearance of table view cells.
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier] autorelease];
}
// Configure the cell.
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
[tableView deselectRowAtIndexPath:[tableView indexPathForSelectedRow] animated:YES];
UITableViewCell *cell = [tableView cellForRowAtIndexPath:indexPath];
if (cell.accessoryType == UITableViewCellAccessoryNone) {
cell.accessoryType = UITableViewCellAccessoryCheckmark;
// Reflect selection in data model
} else if (cell.accessoryType == UITableViewCellAccessoryCheckmark) {
cell.accessoryType = UITableViewCellAccessoryNone;
// Reflect deselection in data model
}
}
#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:#"Provider" 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:#"fullname" ascending:YES];
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];
return fetchedResultsController_;
}
#pragma mark - Memory management
- (void)didReceiveMemoryWarning
{
// Releases the view if it doesn't have a superview.
[super didReceiveMemoryWarning];
// Release any cached data, images, etc that aren't in use.
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc
{
[patientController release];
[clearBtn release];
[setBtn release];
[providerArray release];
[fetchedResultsController_ release];
[managedObjectContext_ release];
[super dealloc];
}
#end
You don't need the line
[self.managedObjectContext insertObject:newManagedObject];
since you've already insertNewObjectForEntityForName before with the newManagedObject.