I experience memory usage increasing each time I scroll up and down my UITableView. I use dequeueReusableCellWithIdentifier, but it doesn't seem it optimizes memory usage. Here's the code:
I thought it was because of UIImageView allocated each time, but when I comment these lines of code and leave only standard UITableViewCell implementation, the problem with memory doesn't go away. Though after leaving the view memory releases (obv it happens only thanks to [self.tableView removeFromSuperview]; method). But while I stay in the view and keep scrolling up and down memory just increases.
#interface ArtistsViewController ()
#property (weak, nonatomic) IBOutlet UITableView *tableView;
#end
#implementation ArtistsViewController
#synthesize fetchedResultsController = _fetchedResultsController;
- (void)viewDidLoad
{
[super viewDidLoad];
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
self.tableView.delegate = self;
self.tableView.dataSource = self;
self.tableView.backgroundColor = [UIColor colorWithRed:11/255.0 green:12/255.0 blue:20/255.0 alpha:1.0];
self.tableView.opaque = NO;
self.tableView.backgroundView = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
- (void)viewDidDisappear:(BOOL)animated {
[super viewDidDisappear:YES];
[self.tableView removeFromSuperview];
}
#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 the number of rows in the section.
id sectionInfo =
[[_fetchedResultsController sections] objectAtIndex:section];
return [sectionInfo numberOfObjects];
}
- (void)loadCellData:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath {
Artist *artist = [_fetchedResultsController objectAtIndexPath:indexPath];
NSLog(#"%#", artist.name);
cell.textLabel.text = [NSString stringWithFormat:#"%#", artist.name];
cell.detailTextLabel.text = [NSString stringWithFormat:#"%lu songs", (unsigned long)[artist.songs count]];
NSString *fileName = [NSString stringWithFormat: #"%#/%#.png", [[NSBundle mainBundle] resourcePath], artist.name];
UIImageView *imgView = [[UIImageView alloc]initWithFrame:CGRectMake(20, 2, 55, 55)];
imgView.image=[UIImage imageWithContentsOfFile:fileName];
[cell.contentView addSubview:imgView];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (!cell) {
NSLog(#"NOCELL");
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
}
//Load cell data
[self loadCellData:cell atIndexPath:indexPath];
//customization
cell.contentView.backgroundColor = cell.selectedBackgroundView.backgroundColor = [UIColor colorWithRed:11/255.0 green:12/255.0 blue:20/255.0 alpha:1.0];
cell.textLabel.textColor = [UIColor colorWithWhite:222/255.0 alpha:1.0];
cell.detailTextLabel.textColor = [UIColor colorWithRed:62/255.0 green:103/255.0 blue:115/255.0 alpha:1.0];
return cell;
}
#pragma mark - fetchedResultsController
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Artist" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:#"name" ascending:YES];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil
cacheName:#"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
Add Custom Cell instead of using the default cell properties.
static NSString *MyIdentifier = #"MyIdentifier";
MyCustomCell *cell = (MyCustomCell *)[tableView dequeueReusableCellWithIdentifier: MyIdentifier];
if (cell == nil) {
NSArray *nib;
nib = [[NSBundle mainBundle] loadNibNamed:#"MyCustomCell"
owner:self options:nil];
for (id oneObject in nib) if ([oneObject isKindOfClass:[MyCustomCell class]])
cell = (YorBillTableCell *)oneObject;
Related
i have tried all solution from stackoverflow.but no use ...
i have one entity called "Notes " .
i need to add search bar to search the thing in my table view...
#interface ViewController ()
{
NSDateFormatter *formatter;
BOOL isChecked;
NSArray *searchResults;
}
#property (nonatomic, strong) UISearchBar *searchBar;
#property (nonatomic, strong) UISearchDisplayController *searchController;
#property (nonatomic) BOOL *isChecked;
#property (strong) NSMutableArray *notes;
#end
#implementation ViewController
#synthesize tableView;
#synthesize addButton;
#synthesize managedObjectContext;
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = #"My Notes";
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];
formatter = [[NSDateFormatter alloc] init];
formatter.doesRelativeDateFormatting = YES;
formatter.locale = [NSLocale currentLocale];
formatter.dateStyle = NSDateFormatterShortStyle;
formatter.timeStyle = NSDateFormatterNoStyle;
CATransition *animation = [CATransition animation];
[animation setDuration:2.0];
[animation setType:kCATransitionPush];
[animation setSubtype:kCATransitionFromTop];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
[[addButton layer] addAnimation:animation forKey:#"SwitchToDown"];
// place search bar coordinates where the navbar is position - offset by statusbar
self.searchBar = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 20, 320, 44)];
UIBarButtonItem *searchButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemSearch target:self action:#selector(toggleSearch)];
self.navigationItem.rightBarButtonItem = searchButton;
self.searchController = [[UISearchDisplayController alloc] initWithSearchBar:self.searchBar contentsController:self];
self.searchController.searchResultsDataSource = self;
self.searchController.searchResultsDelegate = self;
self.searchController.delegate = self;
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Notes"];
NSError *error = nil;
self.notes = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:#"mod_time" ascending:NO];
[self.notes sortUsingDescriptors:[NSArray arrayWithObject:titleSorter]];
NSLog(#"Your Error - %#",error.description);
[tableView reloadData];
}
#pragma mark - Search controller
- (void)searchDisplayControllerWillBeginSearch:(UISearchDisplayController *)controller
{
}
- (void) searchDisplayControllerWillEndSearch:(UISearchDisplayController *)controller
{
// reposition the table where we want after search has completed
// need to reschedule on runloop to rejig the table layout and correct the
// offset and insets given no search bar will be displayed at the top of the controller
// // as we remove it
// dispatch_async(dispatch_get_main_queue(), ^{
// self.tableView.contentInset = UIEdgeInsetsMake([self.topLayoutGuide length], 0, 0, 0);
// self.tableView.contentOffset = CGPointMake(0, -[self.topLayoutGuide length]);
// });
}
- (void)searchDisplayControllerDidEndSearch:(UISearchDisplayController *)controller
{
// [self.searchBar removeFromSuperview];
}
- (void)toggleSearch{
[self.view addSubview:self.searchBar];
[self.searchController setActive:YES animated:YES];
[self.searchBar becomeFirstResponder];
}
- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
{
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"Notes" inManagedObjectContext:_notes];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"notes.title contains[c] %#", searchText];
[fetchRequest setPredicate:predicate];
NSError *error;
NSArray* searchResults = [managedObjectContext executeFetchRequest:fetchRequest error:&error];
}
-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
{
[self filterContentForSearchText:searchString
scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
objectAtIndex:[self.searchDisplayController.searchBar
selectedScopeButtonIndex]]];
return YES;
}
#pragma mark - Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
// Return the number of sections.
return searchResults.count;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
if (tableView == self.searchDisplayController.searchResultsTableView) {
return [searchResults count];
} else {
return self.notes.count;
}
}
- (UITableViewCell *)tableView:(UITableView *)aTableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
TableViewCell *cell = (TableViewCell*)[aTableView dequeueReusableCellWithIdentifier:#"MycellIdentifier"];
if(cell == nil)
{
cell = [[TableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:#"MycellIdentifier"];
}
// Configure the cell...
NSManagedObject *note = [self.notes objectAtIndex:indexPath.row];
NSDate *date = [note valueForKey:#"mod_time"];
NSString *dateString = [formatter stringFromDate:date];
cell.textLabel.text = [note valueForKey:#"title"];
cell.detailTextLabel.text = dateString;
cell.selectionStyle = UITableViewCellSelectionStyleNone;
// cell.accessoryType = UITableViewCellAccessoryCheckmark;
UIButton *button = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 40, 40)];
[button addTarget:self action:#selector(checkBoxClicked:) forControlEvents:UIControlEventTouchUpInside];
[button setImage:[UIImage imageNamed:#"uncheck.png"] forState:UIControlStateNormal];
[cell addSubview:button];
[cell setIndentationLevel:1];
[cell setIndentationWidth:45];
return cell;
}
- (IBAction)addButtonPressed:(id)sender {
AddNoteViewController *addNoteVC = [AddNoteViewController new];
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)cTableView 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 device from table view
[self.notes removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (IBAction)btnClick:(id)sender {
}
-(UITableViewCellEditingStyle) tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return YES;
}
//#pragma Search Methods
//
//- (void)filterContentForSearchText:(NSString*)searchText scope:(NSString*)scope
//{
// NSPredicate *predicate = [NSPredicate predicateWithFormat:#"SELF beginswith[c] %#", searchText];
// // NSPredicate *resultPredicate = [NSPredicate predicateWithFormat:#"contains[c] %#", searchText];
// self.searchResults = [self.notes filteredArrayUsingPredicate:predicate];
//}
//
//-(BOOL)searchDisplayController:(UISearchDisplayController *)controller shouldReloadTableForSearchString:(NSString *)searchString
//{
// [self filterContentForSearchText:searchString
// scope:[[self.searchDisplayController.searchBar scopeButtonTitles]
// objectAtIndex:[self.searchDisplayController.searchBar
// selectedScopeButtonIndex]]];
//
// return YES;
//}
#end
create property for nsfetchviewcontroller in header file
#import <UIKit/UIKit.h>
#interface searchController : UIViewController<UITableViewDataSource,UITableViewDelegate,NSFetchedResultsControllerDelegate,UISearchBarDelegate,UISearchResultsUpdating,UISearchControllerDelegate,UITextFieldDelegate,UITextViewDelegate>{}
#property(nonatomic,retain)NSFetchedResultsController *catefetchedResultsController;
#property (nonatomic, retain) IBOutlet TypeTextfiled *searchCate;
#end
hookup the seachCate textfeild with your xib textfield and set delegate to view controller
in your searchController.m file do this
catName, local_Id are the fields in my cordata and I’m doing query in predicate with them you can use your own columns name
#pragma mark - fetching
- (NSFetchedResultsController *)fetchedResultsControllerCate
{
if (catefetchedResultsController == nil)
{
NSManagedObjectContext* mangedobjectContext=[self appDelegate].managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:frAddCategoryTable
inManagedObjectContext:mangedobjectContext];
NSFetchRequest *request= [[NSFetchRequest alloc] init];
NSString*dateStr=[NSString stringWithFormat:#"%#",[UserDefaluts objectForKey:frautoIncrement]];
NSPredicate *predicate =[NSPredicate predicateWithFormat:#"local_Id==%#",[DateValidator TimestapToDate:dateStr]];
NSSortDescriptor *sd1 = [[NSSortDescriptor alloc] initWithKey:#"local_Id" ascending:YES];
NSSortDescriptor *sd2 = [[NSSortDescriptor alloc] initWithKey:#"catName" ascending:YES];
NSArray *sortDescriptors = [NSArray arrayWithObjects:sd1,sd2, nil];
[request setSortDescriptors:sortDescriptors];
[request setEntity:entity];
[request setPredicate:predicate];
[request setFetchBatchSize:10];
catefetchedResultsController = [[NSFetchedResultsController alloc] initWithFetchRequest:request
managedObjectContext:mangedobjectContext
sectionNameKeyPath:nil
cacheName:nil];
[catefetchedResultsController setDelegate:self];
NSError *error = nil;
if (![catefetchedResultsController performFetch:&error])
{
NSLog(#"Error performing fetch: %#", error);
}
}
return catefetchedResultsController;
}
i this is the delegate method for nsfetchview controller
- (void)controllerDidChangeContent:(NSFetchedResultsController *)controller
{
if (controller==catefetchedResultsController)
{
[self.categoryTable reloadData];
}
}
here when you change in the range of text field this delegete will be wakeup
and it will called the filterCate method for NSPredicate
- (BOOL)textField:(TypeTextfiled *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string{
NSString * searchStr = [textField.text stringByReplacingCharactersInRange:range withString:string];
if(textField == self.searchCate){
[self filterCate:searchStr];
}
return true;
}
please change the NSPredicate as per your requirement and change the name
-(void)filterCate:(NSString*)text
{
filteredTableData = [[NSMutableArray alloc] init];
// Create our fetch request
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
// Define the entity we are looking for
NSManagedObjectContext* mangedobjectContext=[self appDelegate].managedObjectContext;
NSEntityDescription *entity = [NSEntityDescription entityForName:frCategoriesTable
inManagedObjectContext:mangedobjectContext];
[fetchRequest setEntity:entity];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"special==%i",0];
[fetchRequest setPredicate:predicate];
// If we are searching for anything...
if(text.length > 0)
{
// Define how we want our entities to be filtered
predicate = [NSPredicate predicateWithFormat:#"(catName CONTAINS[c] %# AND special==%i)", text,0];
[fetchRequest setPredicate:predicate];
}
NSError *error;
// Finally, perform the load
NSArray* loadedEntities = [mangedobjectContext executeFetchRequest:fetchRequest error:&error];
filteredTableData = [[NSMutableArray alloc] initWithArray:loadedEntities];
[self.CategorTable reloadData];
}
table view
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)sectionIndex {
#warning Incomplete method implementation.
NSArray *sectionCate = [[self fetchedResultsControllerCate] sections];
if (tableView==self.categoryTable) {
if (sectionIndex < [sectionCate count])
{
id <NSFetchedResultsSectionInfo> sectionInfo = [sectionCate objectAtIndex:sectionIndex];
return sectionInfo.numberOfObjects;
}
}
return 0;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
return 70;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
tableView.backgroundColor=[UIColor whiteColor];
static NSString *CellIdentifier = #"Cell";
UITableViewCell *cell=[[UITableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
cell.selectionStyle=UITableViewCellSelectionStyleNone;
tableView.separatorStyle=UITableViewCellSeparatorStyleSingleLine;
tableView.separatorColor=[UIColor colorWithRed:216.0/255.0f green:216.0/255.0f blue:216.0/255.0f alpha:1.0/1.0f];
if(tableView==self.categoryTable){
cell=[self CategoryTablecreateCellFor:cell CellindexPath:indexPath];
}
return cell;
}
-(UITableViewCell*)CategoryTablecreateCellFor:(UITableViewCell*)cell CellindexPath:(NSIndexPath*)indexPath{
AddCategory*cateRecipe=(AddCategory*)[[self fetchedResultsControllerCate] objectAtIndexPath:indexPath];
UILabel *txt=[[UILabel alloc] initWithFrame:CGRectMake(130, 0, 150, 70)];
txt.text=cateRecipe.catName;
txt.textColor=[UIColor darkGrayColor];
[txt setFont: [UIFont fontWithName:#"Helvetica" size:15.0]];
cell.accessoryType=UITableViewCellAccessoryDisclosureIndicator;
[cell.contentView addSubview:txt];
return cell;
}
I have one table view with check mark. when I do check mark one data in my table view my 20,21 data also automatically getting check mark i.e check mark cell reusable.
#interface ViewController ()
{
NSDateFormatter *formatter;
BOOL *check;
}
#property (strong) NSMutableArray *notes;
#end
#implementation ViewController
#synthesize tableView;
#synthesize addButton;
#synthesize catefetchedResultsController;
- (NSManagedObjectContext *)managedObjectContext {
NSManagedObjectContext *context = nil;
id delegate = [[UIApplication sharedApplication] delegate];
if ([delegate performSelector:#selector(managedObjectContext)]) {
context = [delegate managedObjectContext];
}
return context;
}
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.title = #"My Notes";
tableView.dataSource = self;
tableView.delegate = self;
[self.view addSubview:tableView];
formatter = [[NSDateFormatter alloc] init];
formatter.doesRelativeDateFormatting = YES;
formatter.locale = [NSLocale currentLocale];
formatter.dateStyle = NSDateFormatterShortStyle;
formatter.timeStyle = NSDateFormatterNoStyle;
CATransition *animation = [CATransition animation];
[animation setDuration:2.0];
[animation setType:kCATransitionPush];
[animation setSubtype:kCATransitionFromTop];
[animation setTimingFunction:[CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionDefault]];
[[addButton layer] addAnimation:animation forKey:#"SwitchToDown"];
}
- (void)viewDidAppear:(BOOL)animated
{
[super viewDidAppear:animated];
// Fetch the devices from persistent data store
NSManagedObjectContext *managedObjectContext = [self managedObjectContext];
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] initWithEntityName:#"Notes"];
NSError *error = nil;
self.notes = [[managedObjectContext executeFetchRequest:fetchRequest error:&error] mutableCopy];
NSSortDescriptor *titleSorter= [[NSSortDescriptor alloc] initWithKey:#"mod_time" ascending:NO];
[self.notes sortUsingDescriptors:[NSArray arrayWithObject:titleSorter]]
;
NSLog(#"Your Error - %#",error.description);
[tableView reloadData];
}
#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 the number of rows in the section.
return self.notes.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"cell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
UIButton *testButton;
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleSubtitle reuseIdentifier:CellIdentifier];
testButton = [[UIButton alloc]initWithFrame:CGRectMake(5, 5, 40, 40)];
[testButton setImage:[UIImage imageNamed:#"oval"] forState:UIControlStateNormal];
[testButton setImage:[UIImage imageNamed:#"tick"] forState:UIControlStateSelected];
[testButton addTarget:self action:#selector(buttonTouched:) forControlEvents:UIControlEventTouchUpInside];
[cell addSubview:testButton];
[cell setIndentationLevel:1];
[cell setIndentationWidth:45];
cell.selectionStyle = UITableViewCellSelectionStyleNone;
}
// cell.selectionStyle = UITableViewCellSelectionStyleGray;
// Configure the cell...
NSManagedObject *note = [self.notes objectAtIndex:indexPath.row];
NSDate *date = [note valueForKey:#"mod_time"];
NSString *dateString = [formatter stringFromDate:date];
cell.textLabel.text = [note valueForKey:#"title"];
cell.detailTextLabel.text = dateString;
return cell;
}
- (void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
//cell.textLabel.font = [UIFont fontNamesForFamilyName:#"Avenir"];
cell.textLabel.font = [UIFont fontWithName:#"Avenir" size:19.0];
cell.detailTextLabel.font=[UIFont fontWithName:#"Avenir" size:15.0];
}
-(void)buttonTouched:(id)sender
{
UIButton *btn = (UIButton *)sender;
if( [[btn imageForState:UIControlStateNormal] isEqual:[UIImage imageNamed:#"oval"]])
{
[btn setImage:[UIImage imageNamed:#"tick"] forState:UIControlStateNormal];
}
else
{
[btn setImage:[UIImage imageNamed:#"oval"] forState:UIControlStateNormal];
// other statements
}
}
-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
//[[_notes objectAtIndex:indexPath.row] checked];
//[tableView reloadData];
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// _notes.taskArray[indexPath.row][#"CheckStat"] = #YES
}
- (IBAction)addButtonPressed:(id)sender {
AddNoteViewController *addNoteVC = [AddNoteViewController new];
// to remove unused warning....
#pragma unused (addNoteVC)
}
- (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the specified item to be editable.
return YES;
}
- (void)tableView:(UITableView *)cTableView 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 device from table view
[self.notes removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (IBAction)btnClick:(id)sender {
}
#end
Every time in cellForRowAtIndexPath: you should get the check state from _notes.taskArray and reset the check mark for the current row.
You can do it by updating the method:
-(void)tableView:(nonnull UITableView *)tableView didSelectRowAtIndexPath:(nonnull NSIndexPath *)indexPath{
UITableViewCell *cell = (UITableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
BOOL currentStatus = [[chekMarkArray objectAtIndex:indexPath.row] boolValue];
[chekMarkArray replaceObjectAtIndex:indexPath.row withObject:#(!currentStatus)];
UIImage *currentImage = nil;
if ([[chekMarkArray objectAtIndex:indexPath.row] intValue]) {
//cell.accessoryType = UITableViewCellAccessoryCheckmark;
currentImage = [UIImage imageNamed:#"check.png"];
}else{
//cell.accessoryType = UITableViewCellAccessoryNone;
currentImage = [UIImage imageNamed:#"uncheck.png"];
}
//yourCell.yourimageView.image = currentImage;//todo
// [tableView reloadData];
}
I have found the way I need to implement a sections collapsable/expandible tableView, but it is populating the row object from the code itself. I have just created a core data entity and want know to populate the row objects with it.
I have also include a NSFetchedResultsController, but I need help converting this particular code to let me add core data objects. This is my current code:
#import "CollapsableTableViewViewController.h"
#import "CollapsableTableView.h"
#import "CollapsableTableViewAppDelegate.h"
#interface CollapsableTableViewViewController()
#property (nonatomic, retain) NSManagedObjectContext *managedObjectContext;
#end
#implementation CollapsableTableViewViewController
#synthesize fetchedResultsController = _fetchedResultsController;
/*
// The designated initializer. Override to perform setup that is required before the view is loaded.
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
// Custom initialization
}
return self;
}
*/
/*
// Implement loadView to create a view hierarchy programmatically, without using a nib.
- (void)loadView {
}
*/
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
//1
CollapsableTableViewAppDelegate* appDelegate = [UIApplication sharedApplication].delegate;
//2
self.managedObjectContext = appDelegate.managedObjectContext;
self.fetchedResultsController = nil;
NSError *error;
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
CollapsableTableView* tableView = (CollapsableTableView*) myTableView;
tableView.collapsableTableViewDelegate = self;
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"First Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"Second Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"Third Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"Fourth Section"];
// [tableView setIsCollapsed:YES forHeaderWithTitle:#"Fifth Section"];
}
// Override to allow orientations other than the default portrait orientation.
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
// Return YES for supported orientations
return YES;
}
- (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 {
[spinner release];
spinner = nil;
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (void)dealloc {
[spinner release];
[super dealloc];
}
#pragma mark -
#pragma mark UITableViewDataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 10;
}
+ (NSString*) titleForHeaderForSection:(int) section
{
switch (section)
{
case 0 : return #"First Section";
case 1 : return #"Second Section";
case 2 : return #"Third Section";
case 3 : return #"Fourth Section";
case 4 : return #"Fifth Section";
default : return [NSString stringWithFormat:#"Section no. %i",section + 1];
}
}
- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
{
return [CollapsableTableViewViewController titleForHeaderForSection:section];
}
// Uncomment the following two methods to use custom header views.
//- (UILabel *) createHeaderLabel: (UITableView *) tableView :(NSString *)headerTitle {
// UILabel *titleLabel = [[[UILabel alloc] initWithFrame:CGRectZero] autorelease];
// titleLabel.frame =CGRectMake(0, 0, tableView.frame.size.width - 20, 60);
// titleLabel.autoresizingMask = UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
// titleLabel.backgroundColor = [UIColor clearColor];
// titleLabel.textColor = [UIColor whiteColor];
// titleLabel.font=[UIFont fontWithName:#"Helvetica-Bold" size:20];
// titleLabel.text = headerTitle;
// titleLabel.textAlignment = UITextAlignmentRight;
// return titleLabel;
//}
//
//- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
//{
// // create the parent view that will hold header Label
// UIView * customView = [[[UIView alloc] initWithFrame:CGRectMake(0.0, 0.0, tableView.frame.size.width , 60)]autorelease];
// UILabel *titleLabel;
// titleLabel = [self createHeaderLabel: tableView :[CollapsableTableViewViewController titleForHeaderForSection:section]];
//
// [customView addSubview:titleLabel];
//
// UILabel* collapsedLabel = [[[UILabel alloc] initWithFrame:CGRectMake(10,0,50,60)] autorelease];
// collapsedLabel.autoresizingMask = UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin;
// collapsedLabel.backgroundColor = [UIColor clearColor];
// collapsedLabel.textColor = [UIColor whiteColor];
// collapsedLabel.text = #"-";
// collapsedLabel.tag = COLLAPSED_INDICATOR_LABEL_TAG;
// [customView addSubview:collapsedLabel];
//
// customView.tag = section;
// customView.backgroundColor = [UIColor blackColor];
// return customView;
//}
//- (NSString*) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section
//{
// return [NSString stringWithFormat:#"Footer %i",section + 1];
//}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
switch (section)
{
case 2 : return 0;
case 3 : return 30;
default : return 8;
}
}
- (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];
}
// Configure the cell.
switch (indexPath.row)
{
case 0 : cell.textLabel.text = #"First Cell"; break;
case 1 : cell.textLabel.text = #"Second Cell"; break;
case 2 : cell.textLabel.text = #"Third Cell"; break;
case 3 : cell.textLabel.text = #"Fourth Cell"; break;
case 4 : cell.textLabel.text = #"Fifth Cell"; break;
case 5 : cell.textLabel.text = #"Sixth Cell"; break;
case 6 : cell.textLabel.text = #"Seventh Cell"; break;
case 7 : cell.textLabel.text = #"Eighth Cell"; break;
default : cell.textLabel.text = [NSString stringWithFormat:#"Cell %i",indexPath.row + 1];
}
//cell.detailTextLabel.text = ...;
return cell;
}
#pragma mark -
#pragma mark CollapsableTableViewDelegate
- (void) collapsableTableView:(CollapsableTableView*) tableView willCollapseSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner startAnimating];
}
- (void) collapsableTableView:(CollapsableTableView*) tableView didCollapseSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner stopAnimating];
}
- (void) collapsableTableView:(CollapsableTableView*) tableView willExpandSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner startAnimating];
}
- (void) collapsableTableView:(CollapsableTableView*) tableView didExpandSection:(NSInteger) section title:(NSString*) sectionTitle headerView:(UIView*) headerView
{
[spinner stopAnimating];
}
#pragma mark -
#pragma mark IBAction methods
- (IBAction) toggleSection2
{
NSString* sectionTitle = //[NSString stringWithFormat:#"Tag %i",1]; // Use this expression when using custom header views.
[CollapsableTableViewViewController titleForHeaderForSection:1]; // Use this expression when specifying text for headers.
CollapsableTableView* collapsableTableView = (CollapsableTableView*) myTableView;
BOOL isCollapsed = [[collapsableTableView.headerTitleToIsCollapsedMap objectForKey:sectionTitle] boolValue];
[collapsableTableView setIsCollapsed:! isCollapsed forHeaderWithTitle:sectionTitle];
}
- (NSFetchedResultsController *)fetchedResultsController {
if (_fetchedResultsController != nil) {
return _fetchedResultsController;
}
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity = [NSEntityDescription
entityForName:#"ToDoItems" inManagedObjectContext:self.managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sort = [[NSSortDescriptor alloc]
initWithKey:#"tdText" ascending:NO];
[fetchRequest setSortDescriptors:[NSArray arrayWithObject:sort]];
[fetchRequest setFetchBatchSize:20];
NSFetchedResultsController *theFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:self.managedObjectContext sectionNameKeyPath:nil
cacheName:#"Root"];
self.fetchedResultsController = theFetchedResultsController;
_fetchedResultsController.delegate = self;
return _fetchedResultsController;
}
#end
One way to do this is by storing the objects that you fetched into an Array or dictionary and later moving it into cell.
For example, declare NSArray *fetchedResults in your .h file. Then store fetched results into this array as shown below.
if (![[self fetchedResultsController] performFetch:&error]) {
// Update to handle the error appropriately.
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
exit(-1); // Fail
}
*fetchedResults = [self.managedObjectContext executeFetchRequest:fetchRequest error:&error];
Later, fill your uitableviewcell rows from the array
- (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];
}
// Configure the cell.
// Replacing switch with below code will populate your cell rows in the order in which data is retrieved from core data.
cell.textLabel.text = [self.fetchedResults objectAtIndex:(indexPath.row)] ;
......
......
}
You can add your own logic to get correct content into each rows.
I am using core data with an entity and several attributes. One of the attributes is named ToDoStatus. The list of the entity records are shown on a tableview and I want to implement following requirement:
1. When the user makes a long press on a cell (about 1 second), the record pressed must change its ToDoStatus value to "Done" and then reload the tableview not showing records with ToDoStatus = "Done".
This is my current code:
#import "RootViewController.h"
#import "AddToDoViewController.h"
#import "EditToDoViewController.h"
#import "MenuViewController.h"
#interface RootViewController ()
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath;
#end
#implementation RootViewController
#synthesize fetchedResultsController, managedObjectContext,AddToDoButton,MenuToDoButton;
#pragma mark -
#pragma mark View lifecycle
- (void)viewDidLoad {
[super viewDidLoad];
// [self setTitle:#"Today"];
[[self navigationItem] setRightBarButtonItem:[self editButtonItem]];
self.editButtonItem.tintColor = [UIColor redColor];
UILabel *lblTitle = [[UILabel alloc] init];
lblTitle.text = #"Today";
lblTitle.backgroundColor = [UIColor clearColor];
lblTitle.textColor = [UIColor blueColor];
lblTitle.shadowColor = [UIColor whiteColor];
lblTitle.shadowOffset = CGSizeMake(0, 1);
lblTitle.font = [UIFont fontWithName:#"Noteworthy" size:25.0];
[lblTitle sizeToFit];
self.navigationItem.titleView = lblTitle;
[self.editButtonItem setTitleTextAttributes:[NSDictionary dictionaryWithObjectsAndKeys:
[UIFont fontWithName:#"Noteworthy" size:20], NSFontAttributeName,
[UIColor blueColor], NSForegroundColorAttributeName,
nil]
forState:UIControlStateNormal];
self.tableView.delegate = self;
self.tableView.dataSource = self;
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
- (void) viewWillAppear:(BOOL)animated{
NSError *error = nil;
if (![[self fetchedResultsController] performFetch:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
[self.tableView reloadData];
}
- (void)configureCell:(UITableViewCell *)cell atIndexPath:(NSIndexPath *)indexPath
{
NSManagedObject *managedObject = [fetchedResultsController objectAtIndexPath:indexPath];
[[cell textLabel] setText:[[managedObject valueForKey:#"thingName"] description]];
NSString *myString = [NSString stringWithFormat:#"%#",[[managedObject valueForKey:#"todoYear"] description]];
UIButton *urgentButton = [[UIButton alloc]initWithFrame:CGRectMake(15, 25, 18, 18)];
[urgentButton setImage:[UIImage imageNamed:#"urgent"]forState:UIControlStateNormal];
[cell addSubview:urgentButton];
UIButton *yellowButton = [[UIButton alloc]initWithFrame:CGRectMake(305, 5, 10, 40)];
[yellowButton setImage:[UIImage imageNamed:#"Red"]forState:UIControlStateNormal];
[cell addSubview:yellowButton];
UIButton *doneButton = [[UIButton alloc]initWithFrame:CGRectMake(33, 27, 18, 18)];
[doneButton setImage:[UIImage imageNamed:#"alldone"]forState:UIControlStateNormal];
[cell addSubview:doneButton];
UIButton *doneButton2 = [[UIButton alloc]initWithFrame:CGRectMake(53, 27, 18, 18)];
[doneButton2 setImage:[UIImage imageNamed:#"alldone"]forState:UIControlStateNormal];
[cell addSubview:doneButton2];
UIButton *doneButton3 = [[UIButton alloc]initWithFrame:CGRectMake(71, 27, 18, 18)];
[doneButton3 setImage:[UIImage imageNamed:#"urgent"]forState:UIControlStateNormal];
[cell addSubview:doneButton3];
[[cell detailTextLabel] setText:#" "];
[cell setSelectionStyle:UITableViewCellSelectionStyleNone];
cell.textLabel.textColor = [UIColor blueColor];
cell.textLabel.font = [UIFont fontWithName:#"Noteworthy" size:22.0f];
cell.detailTextLabel.font = [UIFont fontWithName:#"Noteworthy" size:15.0f];
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
EditToDoViewController *detailViewController = [[EditToDoViewController alloc] initWithNibName:#"EditToDoViewController" bundle:nil];
NSManagedObject *selectedObject = [[self fetchedResultsController] objectAtIndexPath:indexPath];
detailViewController.selectedObject = selectedObject;
//[self.navigationController pushViewController:detailViewController animated:YES];
[self presentViewController:detailViewController animated:YES completion:nil];
}
#pragma mark -
#pragma mark Table view data source
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return [[fetchedResultsController sections] count];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
id <NSFetchedResultsSectionInfo> sectionInfo = [[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:#"Cell"] autorelease];
}
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
NSManagedObjectContext *context = [fetchedResultsController managedObjectContext];
[context deleteObject:[fetchedResultsController objectAtIndexPath:indexPath]];
NSError *error = nil;
if (![context save:&error])
{
NSLog(#"Unresolved error %#, %#", error, [error userInfo]);
abort();
}
}
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void)tableView:(UITableView *)tableView
moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)destinationIndexPath;
{
NSMutableArray *things = [[fetchedResultsController fetchedObjects] mutableCopy];
// Grab the item we're moving.
NSManagedObject *thing = [[self fetchedResultsController] objectAtIndexPath:sourceIndexPath];
// Remove the object we're moving from the array.
[things removeObject:thing];
// Now re-insert it at the destination.
[things insertObject:thing atIndex:[destinationIndexPath row]];
// All of the objects are now in their correct order. Update each
// object's displayOrder field by iterating through the array.
int i = 0;
for (NSManagedObject *mo in things)
{
[mo setValue:[NSNumber numberWithInt:i++] forKey:#"displayOrder"];
}
[things release], things = nil;
[managedObjectContext save:nil];
}
#pragma mark -
#pragma mark Fetched results controller
- (IBAction)AddToDoAction:(id)sender {
AddToDoViewController *viewController = [[AddToDoViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
}
#pragma mark Fetched results controller
- (IBAction)MenuToDoAction:(id)sender {
MenuViewController *viewController = [[MenuViewController alloc] init];
[self presentViewController:viewController animated:YES completion:nil];
}
- (NSFetchedResultsController *)fetchedResultsController
{
if (fetchedResultsController) return fetchedResultsController;
NSFetchRequest *fetchRequest = [[NSFetchRequest alloc] init];
NSEntityDescription *entity =
[NSEntityDescription entityForName:#"FavoriteThing"
inManagedObjectContext:managedObjectContext];
[fetchRequest setEntity:entity];
NSSortDescriptor *sortDescriptor =
[[NSSortDescriptor alloc] initWithKey:#"displayOrder"
ascending:YES];
NSArray *sortDescriptors = [[NSArray alloc]
initWithObjects:sortDescriptor, nil];
NSNumber *yearBuscado = #2013;
NSNumber *mesBuscado = #12;
NSNumber *diaBuscado = #13;
NSString *tipourgente = #"Urgent";
NSString *tipocolor = #"Yellow";
NSPredicate *yearPredicate = [NSPredicate predicateWithFormat:#"todoYear == %#", yearBuscado];
NSPredicate *monthPredicate = [NSPredicate predicateWithFormat:#"todoMonth == %#", mesBuscado];
NSPredicate *dayPredicate = [NSPredicate predicateWithFormat:#"todoDay == %#", diaBuscado];
NSPredicate *urgentPredicate = [NSPredicate predicateWithFormat:#"urgent == %#", tipourgente];
NSPredicate *colorPredicate = [NSPredicate predicateWithFormat:#"color == %#", tipocolor];
[fetchRequest setSortDescriptors:sortDescriptors];
NSPredicate *busqueda = [NSCompoundPredicate andPredicateWithSubpredicates:#[yearPredicate, monthPredicate,dayPredicate,urgentPredicate]];
[fetchRequest setPredicate:busqueda];
NSFetchedResultsController *aFetchedResultsController =
[[NSFetchedResultsController alloc] initWithFetchRequest:fetchRequest
managedObjectContext:managedObjectContext
sectionNameKeyPath:nil cacheName:nil];
aFetchedResultsController.delegate = self;
[self setFetchedResultsController:aFetchedResultsController];
[aFetchedResultsController release];
[fetchRequest release];
[sortDescriptor release];
[sortDescriptors release];
return fetchedResultsController;
}
- (void)dealloc {
[fetchedResultsController release];
[managedObjectContext release];
[super dealloc];
}
#end
Here is how you handle a long press:
- (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:#"Cell"] autorelease];
}
UILongPressGestureRecognizer *lpgr = [[UILongPressGestureRecognizer alloc]
initWithTarget:self action:#selector(handleLongPress:)];
lpgr.minimumPressDuration = 1.0; //seconds
[cell addGestureRecognizer:lpgr];
[self configureCell:cell atIndexPath:indexPath];
return cell;
}
-(void)handleLongPress:(UILongPressGestureRecognizer *)gestureRecognizer
{
CGPoint p = [gestureRecognizer locationInView:self.tableView];
NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
if (indexPath == nil)
NSLog(#"long press on table view but not on a row");
else
{
if (gestureRecognizer.state == UIGestureRecognizerStateEnded) {
NSLog(#"UIGestureRecognizerStateEnded");
//Do Whatever You want on End of Gesture
}
else if (gestureRecognizer.state == UIGestureRecognizerStateBegan){
UIAlertView *alert = [[UIAlertView alloc] initWithTitle: #"Announcement" message: #"You have long-pressed the row...!" delegate: nil cancelButtonTitle:#"OK" otherButtonTitles:nil];
[alert show];
[alert release];
NSLog(#"UIGestureRecognizerStateBegan.");
NSLog(#"long press on table view at row %d", indexPath.row);
// Update ToDoStatus
[self.tableView reloadData];
//Do Whatever You want on Began of Gesture
}
}
}
Your model will keep track of ToDoStatus in your model and then decide how that will be displayed in the UI.
I don't get it. The cellForRowAtIndexPath function's indexPath parameter is always 0. I currently have 7 rows in my table. What my table shows is 7x the first table row. What could cause the indexPath to always be zero?
#implementation SitesViewController
#synthesize sites, siteCell;
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [sites count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"SiteCell"];
if (cell == nil) {
[[NSBundle mainBundle] loadNibNamed:#"SiteCell" owner:self options:nil];
cell = siteCell;
self.siteCell = nil;
}
Site *site = [sites objectAtIndex:indexPath.section];
UILabel *siteNameLabel;
siteNameLabel = (UILabel *)[cell viewWithTag:1];
siteNameLabel.text = site.siteName;
return cell;
}
- (void)viewDidLoad
{
[super viewDidLoad];
NSManagedObjectContext *context = [[DigMateAppDelegate sharedAppDelegate] managedObjectContext];
NSEntityDescription *entityDesc = [NSEntityDescription entityForName:#"Sites" inManagedObjectContext:context];
NSFetchRequest *request = [[NSFetchRequest alloc] init];
[request setEntity:entityDesc];
NSError *error;
sites = [context executeFetchRequest:request error:&error];
}
Since you have 7 rows and I assume 1 section then you should get record from array based on row index, not section. So the following line in cellForRowAtIndexPath: method:
Site *site = [sites objectAtIndex:indexPath.section];
should be:
// Use indexPath's row instead of section!
Site *site = [sites objectAtIndex:indexPath.row];