I am trying to make my UITableView Editable but I'm having some trouble with the code, specifically with the commitEditingStyle method. It is not working I think the method I have is only for plist and not for an array by itself.
#import "RoutineTableViewController.h"
#import "AlertPrompt.h"
#implementation RoutineTableViewController
#synthesize myArray;
- (void)dealloc
{
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
- (void)viewDidLoad
{
myArray = [[NSMutableArray alloc] init];
myData = [[NSMutableArray arrayWithContentsOfFile:#"mydata"] retain];
if (myData == nil)
{
myData = [NSMutableArray array];
}
[super viewDidLoad];
UIBarButtonItem * addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(showPrompt)];
[self.navigationItem setLeftBarButtonItem:addButton];
[addButton release];
self.navigationItem.rightBarButtonItem = self.editButtonItem;
}
-(void)showPrompt
{
AlertPrompt *prompt = [AlertPrompt alloc];
prompt = [prompt initWithTitle:#"Add Workout Day" message:#"\n \n Please enter title for workout day" delegate:self cancelButtonTitle:#"Cancel" okButtonTitle:#"Add"];
[prompt show];
[prompt release];
}
- (void)alertView:(UIAlertView *)alertView willDismissWithButtonIndex:(NSInteger)buttonIndex
{
if (buttonIndex != [alertView cancelButtonIndex])
{
NSString *entered = [(AlertPrompt *)alertView enteredText];
NSLog([NSString stringWithFormat:#"%#", entered]);
if(myData && entered)
{
[myArray addObject:entered];
[tableView reloadData];
}
}
}
- (void)viewDidUnload
{
[super viewDidUnload];
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
}
- (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 [myArray 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];
}
cell.textLabel.text = [self.myArray objectAtIndex:indexPath.row];
return cell;
}
/*
// 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;
}
*/
// Override to support editing the table view.
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
[self.list removeObjectAtIndex:row];
[tableView deleteRowsAtIndexPaths:[myArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
As prevoulsy ansewered; self.list has to be Mutable.
The next thing you need to do is "warn" the tableView about the updates.
So you would do it like this:
- (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
NSUInteger row = [indexPath row];
[self.list removeObjectAtIndex:row];
//Notice we "warn" the tableView
[tableView beginUpdates];
[tableView deleteRowsAtIndexPaths:[NSMutableArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
//We also tell the table the updates are done so it can do the proper animations
[tableView endUpdates];
}
Remember you first change the model and then update the tableView with the add, reload and delete methods in between a beginUpdates and endUpdates.
What type is self.list? It needs to be an NSMutableArray for a call to 'removeObjectAtIndex' to be valid.
There is no .plist involved here, that's just the name of this NSMutableArray. Your sample code assumes you are declaring an NSMutableArray called list in your #interface...
#interface RoutineTableViewController : UIViewController {
NSMutableArray *list;
}
#property (nonatomic, retain) NSMutableArray *list;
#end
... and synthesizing it (and filling it with something) somewhere in your code.
Related
This is my custom table view cell, I want to change those values in every 1 minute (values will load from server). I have already set an Nstimer and tried to reload the tableview. Data in my array is changing fine, but value in the uitableviewcell is not changing.
Code:
Tableviewcontroller.m
-(void) loadView
{
parsejson = [ParseJson alloc];
defaults=[NSUserDefaults standardUserDefaults];
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
listtimer = [NSTimer scheduledTimerWithTimeInterval:60.0 // start timer ( interval 2 secs )
target:self
selector:#selector(reloadlist:)
userInfo:nil
repeats:YES];
}
- (void)reloadlist:(NSTimer*)timer
{
NSLog(#"list reload " );
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
//UITableView *tv = (UITableView *)self.view;
[self.tableview reloadData];
// NSIndexPath *a = [NSIndexPath indexPathForRow:0 inSection:0]; // I wanted to update this cell specifically
// NearestListCell *c = (NearestListCell *)[tv cellForRowAtIndexPath:a];
//c.count=[usercount objectAtIndex:0];
//[tv beginUpdates];
//// [tv reloadRowsAtIndexPaths:usercount withRowAnimation:UITableViewRowAnimationRight];
//[tv endUpdates];
// [tv 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 [usercount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NearmeListIdentifier";
listCell *cell = (listCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"listCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.text.text = [items objectAtIndex:indexPath.row];
cell.data11.text = [usercount objectAtIndex:indexPath.row];
cell.data22.text = #" 0.0 ";
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
Viewcontroller.h
#interface Viewcontroller : UIViewController
{
Tableviewcontroller *Tablecontroller;
IBOutlet UITableView *myTable;
}
#end
Viewcontroller.m
-(void)viewDidLoad
{
[super viewDidLoad];
defaults = [NSUserDefaults standardUserDefaults];
if (Tablecontroller == nil)
{
Tablecontroller = [[Tableviewcontroller alloc] init];
}
[myTable setDataSource:Tablecontroller];
[myTable setDelegate:Tablecontroller];
Tablecontroller.view = Tablecontroller.tableView;
}
Please try this code : its working fine here
/* FirstTVContoller.h */
#import <Foundation/Foundation.h>
#interface FirstTVContoller : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
NSMutableArray *items;
}
#end
/* FirstTVContoller.m */
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#implementation FirstTVContoller
-(void) loadView
{
if (items == nil) {
items = [[NSMutableArray arrayWithObjects:#"1",#"2",#"3",#"4",#"5",#"6",#"6",#"8",#"9",#"10",#"11",#"12",#"13",#"14",#"15",#"16",#"17",nil] retain];
}
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return [items count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewStylePlain reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"1.%#" ,[items objectAtIndex:indexPath.row]];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
[items removeObjectAtIndex:indexPath.row];
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
-(void) dealloc
{
[items release];
[super dealloc];
}
#end
/* SecondTVController.h */
#import <Foundation/Foundation.h>
#interface SecondTVController : UITableViewController <UITableViewDataSource, UITableViewDelegate>{
int numberOfCells;
}
#end
/* SecondTVController.m */
#import "SecondTVController.h"
#implementation SecondTVController
-(void) viewDidLoad
{
numberOfCells = 20;
}
-(NSInteger) numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(NSInteger) tableView:(UITableView *)table numberOfRowsInSection:(NSInteger)section
{
return numberOfCells;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:#"MyIdentifier"];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellSelectionStyleNone reuseIdentifier:#"MyIdentifier"];
}
cell.textLabel.text = [NSString stringWithFormat:#"2.%d", indexPath.row];
return cell;
}
-(void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (UITableViewCellEditingStyle)tableView:(UITableView *)tableView editingStyleForRowAtIndexPath:(NSIndexPath *)indexPath {
return UITableViewCellEditingStyleDelete;
}
- (void)tableView:(UITableView *)tv commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath {
if(editingStyle == UITableViewCellEditingStyleDelete) {
//Delete the object from the table.
numberOfCells -=1;
[tv deleteRowsAtIndexPaths:[NSArray arrayWithObject:indexPath] withRowAnimation:UITableViewRowAnimationRight];
}
}
#end
/* TwoTableViewsViewController.h */
#import <UIKit/UIKit.h>
#import "FirstTVContoller.h"
#import "SecondTVController.h"
#interface TwoTableViewsViewController : UIViewController{
FirstTVContoller *firstController;
SecondTVController *secondController;
IBOutlet UITableView *firstTable;
IBOutlet UITableView *secondTable;
}
#end
/* TwoTableViewsViewController.m */
#import "TwoTableViewsViewController.h"
#implementation TwoTableViewsViewController
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad {
[super viewDidLoad];
if (firstController == nil) {
firstController = [[FirstTVContoller alloc] init];
}
if (secondController == nil) {
secondController = [[SecondTVController alloc] init];
}
[firstTable setDataSource:firstController];
[secondTable setDataSource:secondController];
[firstTable setDelegate:firstController];
[secondTable setDelegate:secondController];
firstController.view = firstController.tableView;
secondController.view = secondController.tableView;
}
- (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)dealloc {
[firstController release];
[secondController release];
[firstTable release];
[secondTable release];
[super dealloc];
}
Let me know if you still face any problems. This will work for sure for n-no. of UITableViews.
ViewController.h
#import <UIKit/UIKit.h>
#interface ViewController : UITableViewController
#end
ViewController.m
#import "ViewController1.h"
#implementation ViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return [usercount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"NearmeListIdentifier";
listCell *cell = (listCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"listCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.text.text = [items objectAtIndex:indexPath.row];
cell.data11.text = [usercount objectAtIndex:indexPath.row];
cell.data22.text = #" 0.0 ";
return cell;
}
- (void)reloadlist:(NSTimer*)timer
{
NSLog(#"list reload " );
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
[self.tableView reloadData];
}
-(void) loadView
{
parsejson = [ParseJson alloc];
defaults=[NSUserDefaults standardUserDefaults];
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
listtimer = [NSTimer scheduledTimerWithTimeInterval:60.0 // start timer ( interval 2 secs )
target:self
selector:#selector(reloadlist:)
userInfo:nil
repeats:YES];
}
Please try this code and let me know if you face any problems.Thanks
Why don't you try
[self.tableView reloadData];
instead of
UITableView *tv = (UITableView *)self.view;
[tv reloadData];
Only if your super class is UITableViewController.If not then make an outlet for tableView and reload table through it.
have you used this 'setNeedsDisplay' as
[cell.data11 setNeedsDisplay] if cellForRow is calling.
Please change below code :
/* TwoTableViewsViewController.m */
- (void)viewDidLoad {
[super viewDidLoad];
if (firstController == nil) {
firstController = [[FirstTVContoller alloc] init];
}
if (secondController == nil) {
secondController = [[SecondTVController alloc] init];
}
[firstTable setDataSource:firstController];
[secondTable setDataSource:secondController];
[firstTable setDelegate:firstController];
[secondTable setDelegate:secondController];
firstController.view = firstController.tableView;
secondController.view = secondController.tableView;
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(reloadData:) name:#"ReloadFirstTable" object:nil];
}
-(void)reloadData:(id)sender
{
[firstTable reloadData];
}
/* FirstTVContoller.m */
- (void)reloadlist:(NSTimer*)timer
{
NSLog(#"list reload " );
self.items = [NSMutableArray arrayWithObjects:#"data1",#" data2 ", nil];
[[NSNotificationCenter defaultCenter] postNotificationName:#"ReloadFirstTable" object:nil];
}
Please use NSNotificationCenter to reload Data.
I fixed the issue. Forgot to reload UITableview object in viewcontroller. I removed the NStimer from Tableviewcontroller.m and placed it in the Viewcontroller.m.
The changed code:
TableViewController.m
-(void) loadView
{
parsejson = [ParseJson alloc];
defaults=[NSUserDefaults standardUserDefaults];
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:
[parsejson getdata:[defaults valueForKey:#"userid"]],#" 0 ", nil];
**// removed the nstimer from here.**
}
#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 [usercount count];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
// Added these 2 lines of code here.
items=[NSArray arrayWithObjects:#" data1",#" data2 ", nil];
usercount=[NSArray arrayWithObjects:[parsejson getNearestUsercount:[defaults valueForKey:#"userid"]],#" 0 ", nil];
static NSString *CellIdentifier = #"NearmeListIdentifier";
listCell *cell = (listCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
NSArray *nib = [[NSBundle mainBundle] loadNibNamed:#"listCell" owner:self options:nil];
cell = [nib objectAtIndex:0];
}
cell.text.text = [items objectAtIndex:indexPath.row];
cell.data11.text = [usercount objectAtIndex:indexPath.row];
cell.data22.text = #" 0.0 ";
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
[tableView deselectRowAtIndexPath:indexPath animated:YES];
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
Viewcontroller.m
-(void)viewDidLoad
{
[super viewDidLoad];
defaults = [NSUserDefaults standardUserDefaults];
if (Tablecontroller == nil)
{
Tablecontroller = [[Tableviewcontroller alloc] init];
}
[myTable setDataSource:Tablecontroller];
[myTable setDelegate:Tablecontroller];
Tablecontroller.view = Tablecontroller.tableView;
// I Put the Nstimer here.
aTimer = [NSTimer scheduledTimerWithTimeInterval:2.0 // start timer ( interval 2 secs )
target:self
selector:#selector(timerTicked:)
userInfo:nil
repeats:YES];
}
- (void)timerTicked:(NSTimer*)timer
{
[myTable.self reloadData];
}
Thank You all for helping me.
I want to save everything in a UITableView controller, with a button, I dont know how to do that. I know it has a saving method, but when you press back to the homescreen of the app, and go back to the viewcontroller, the text is gone, or when i deleted something its still there.
code in my .m file
#import "HomeWorkViewController.h"
#interface HomeWorkViewController ()
#end
#implementation HomeWorkViewController
#synthesize adView;
#synthesize myTableView, numbers;
-(void) viewDidLoad
{
adView.delegate=self;
[super viewDidLoad];
self.navigationItem.leftBarButtonItem = self.editButtonItem;
// check here if key exists in the defaults or not, if yes the retrieve results in array
if([[NSUserDefaults standardUserDefaults] objectForKey:#"numberArray"] != nil) {
self.numbers = [NSMutableArray arrayWithArray:[[NSUserDefaults standardUserDefaults] objectForKey:#"numberArray"]];
}
//Register for the notification when user go to background or minimize the app, just save the array objects in the defaults
[[NSNotificationCenter defaultCenter] addObserver:self
selector:#selector(appWillGoToBackground:)
name:UIApplicationWillResignActiveNotification object:[UIApplication sharedApplication]];
//Add the Add button
UIBarButtonItem * addButton = [[UIBarButtonItem alloc]
initWithBarButtonSystemItem:UIBarButtonSystemItemAdd
target: self action: #selector(insertNewObject)];
self.navigationItem.rightBarButtonItem = addButton;
}
-(void)setEditing:(BOOL)editing animated:(BOOL)animated {
[super setEditing:editing animated:animated];
[self.myTableView setEditing:editing animated:animated];
}
-(void)appWillGoToBackground:(NSNotification *)note {
NSLog(#"terminate");
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:self.numbers forKey:#"numberArray"];
[defaults synchronize];
}
-(void)insertNewObject{
//Display a UIAlertView
UIAlertView *alert = [[UIAlertView alloc] initWithTitle:#"Enter HomeWork" message: #"" delegate:self cancelButtonTitle:#"Cancel" otherButtonTitles:#"Ok", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
[alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
//Only perform the following actions if the user hits the ok button
if (buttonIndex == 1)
{
NSString * tmpTextField = [alertView textFieldAtIndex:0].text;
if(!self. numbers){
self.numbers = [[NSMutableArray alloc]init];
}
[self.numbers insertObject:tmpTextField atIndex:0];
NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.myTableView insertRowsAtIndexPaths:#[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];
}
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
return 1;
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
return self.numbers.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];
}
cell.textLabel.text = [self.numbers objectAtIndex:indexPath.row];
return cell;
}
-(BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
-(void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
//remove our NSMutableArray
[self.numbers removeObjectAtIndex:indexPath.row];
//remove from our tableView
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
}
}
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath
toIndexPath:(NSIndexPath *)toIndexPath
{
}
-(void)bannerViewDidLoadAd:(ADBannerView *)banner
{
adView.hidden=FALSE;
NSLog(#"Has ad, showing");
}
-(void)bannerView:(ADBannerView *)banner didFailToReceiveAdWithError:(NSError *)error
{
adView.hidden=TRUE;
NSLog(#"Has no ads, hiding");
}
-(void)dealloc
{
[adView release];
[super dealloc];
}
- (void)viewDidUnload {
[super viewDidUnload];
}
#end
Looks like you are only saving your data when the application enters the background. If you want to persist the data immediately instead of just when the app closes, just write your array to NSUserDefaults in alertView:clickedButtonAtIndex:
RootViewController.h
#import <UIKit/UIKit.h>
#interface RootViewController : UITableViewController {
NSMutableArray *petsArray;
}
#property (nonatomic, strong) NSMutableArray *petsArray;
#end
RootViewController.m
#import "RootViewController.h"
#import "PetsViewController.h"
#interface RootViewController ()
#end
#implementation RootViewController
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
petsArray = [[NSMutableArray alloc] init];
[petsArray addObject:#"Dog"];
[petsArray addObject:#"Cat"];
[petsArray addObject:#"Snake"];
[self setTitle:#"PETS !"];
// 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)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#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 [petsArray 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];
}
// Configure the cell...
cell.textLabel.text = [petsArray objectAtIndex:indexPath.row];
return cell;
}
#pragma mark - Table view delegate
I think that the problem is in didSelectRowAtIndexPath which I can't use in storyboarded project.
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
PetsViewController *pets = [[PetsViewController alloc] initWithNibName:#"PetsViewController" bundle:nil];
if ([[petsArray objectAtIndex:indexPath.row] isEqual:#"Dog"]) {
pets.petsInt = 0;
[pets setTitle:[petsArray objectAtIndex:indexPath.row]];
}
if ([[petsArray objectAtIndex:indexPath.row] isEqual:#"Cat"]) {
pets.petsInt = 1;
[pets setTitle:[petsArray objectAtIndex:indexPath.row]];
}
if ([[petsArray objectAtIndex:indexPath.row] isEqual:#"Snake"]) {
pets.petsInt = 2;
[pets setTitle:[petsArray objectAtIndex:indexPath.row]];
}
[self.navigationController pushViewController:pets animated:YES];
}
#end
PetsViewController.h
#import <UIKit/UIKit.h>
#interface PetsViewController : UITableViewController {
NSMutableArray *dogArray;
NSMutableArray *catArray;
NSMutableArray *snakeArray;
int petsInt;
}
#property int petsInt;
#end
PetsViewController.m
#import "PetsViewController.h"
#interface PetsViewController ()
#end
#implementation PetsViewController
#synthesize petsInt;
- (id)initWithStyle:(UITableViewStyle)style
{
self = [super initWithStyle:style];
if (self) {
// Custom initialization
}
return self;
}
- (void)viewDidLoad
{
[super viewDidLoad];
dogArray = [[NSMutableArray alloc] initWithObjects:#"HAF",#"hafo", #"hafinio", nil];
catArray = [[NSMutableArray alloc] initWithObjects:#"MYAU",#"myainio", #"mya lya lya", nil];
snakeArray = [[NSMutableArray alloc] initWithObjects:#"fshhhhh",#"fsssss", #"xrt", nil];
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
// e.g. self.myOutlet = nil;
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#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.
if (petsInt == 0) return [dogArray count];
if (petsInt == 1) return [catArray count];
if (petsInt == 2) return [snakeArray count];
[self.tableView reloadData];
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"PetsCell";
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];
}
// Configure the cell...
if (petsInt == 0) cell.textLabel.text = [dogArray objectAtIndex:indexPath.row];
if (petsInt == 1) cell.textLabel.text = [catArray objectAtIndex:indexPath.row];
if (petsInt == 2) cell.textLabel.text = [snakeArray objectAtIndex:indexPath.row];
[cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
return cell;
}
#pragma mark - Table view delegate
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
// Navigation logic may go here. Create and push another view controller.
/*
<#DetailViewController#> *detailViewController = [[<#DetailViewController#> alloc] initWithNibName:#"<#Nib name#>" bundle:nil];
// ...
// Pass the selected object to the new view controller.
[self.navigationController pushViewController:detailViewController animated:YES];
*/
}
#end
[self performSegueWithIdentifier:#"SEGUE_NAME" sender:self];
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
if ([[segue identifier] isEqualToString:#"SEGUE_NAME"]) {
PetsViewController *pets = [segue destinationViewController];
[pets setPetsInt:0];
[pets setTitle:#"Title"];
}
}
-(void) prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender{
NSIndexPath *indexPath = self.tableView.indexPathForSelectedRow;
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 0;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 1;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 2;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
if ([[gazel objectAtIndex:indexPath.row] isEqual:#"<էրեբունի> Օդանավակայան"]) {
KangarList *kang = [segue destinationViewController];
kang.kangarInt = 3;
[kang setTitle:[gazel objectAtIndex:indexPath.row]];
}
}
i have tried many ways and i finaly realized the right method, but it works only when under view did load method objects have only one description but if it hase something like thise
gazel = [[NSMutableArray alloc] init];
Data *data = [[Data alloc] init];
data.title = #"<էրեբունի> Օդանավակայան";
data.subtitle = #"Հարաֆ Արևմտյան Թաղամաս";
data.photo = 1;
[gazel addObject:data];
its not working
I'm trying to be able to insert an object into my table, but it crashes because of an uncaught exception whenever I hit the add button. It says
Attempt to insert row 0 into section 0, but there are only 0 rows in section 0 after the update
Here's my main view controller which handles all my table stuff...
#import "MasterViewController.h"
#import "DetailViewController.h"
#define kFileName #"steakNames.plist"
#interface MasterViewController () {
NSMutableArray *_objects;
}
#end
#implementation MasterViewController
#synthesize steakName;
- (NSString *)dataFilePath {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentationDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
return [documentsDirectory stringByAppendingPathComponent:kFileName];
}
- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
if (self) {
self.title = NSLocalizedString(#"Master", #"Master");
}
return self;
}
- (void)viewDidLoad
{
NSString *filePath = [self dataFilePath];
if ([[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
_objects = [[NSMutableArray alloc] initWithContentsOfFile:filePath];
}
UIApplication *app = [UIApplication sharedApplication];
[[NSNotificationCenter defaultCenter] addObserver:self selector:#selector(applicationWillResignActive:) name:UIApplicationWillResignActiveNotification object:app];
[super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.
self.navigationItem.leftBarButtonItem = self.editButtonItem;
UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:#selector(insertNewObject:)];
self.navigationItem.rightBarButtonItem = addButton;
}
- (void)viewDidUnload
{
[super viewDidUnload];
// Release any retained subviews of the main view.
}
- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
return (interfaceOrientation != UIInterfaceOrientationPortraitUpsideDown);
}
- (void)insertNewObject:(id)sender
{
if (!steakName) {
steakName = #"No name";
}
[_objects insertObject:[self steakName] atIndex:0];
NSIndexPath *indexPath = [NSIndexPath indexPathForRow:0 inSection:0];
[self.tableView insertRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationAutomatic];
}
#pragma mark - Table View
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return _objects.count;
}
// 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];
cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
}
NSDate *object = [_objects objectAtIndex:indexPath.row];
cell.textLabel.text = [object description];
return cell;
}
- (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 *)tableView commitEditingStyle: (UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete) {
[_objects removeObjectAtIndex:indexPath.row];
[tableView deleteRowsAtIndexPaths:#[indexPath] withRowAnimation:UITableViewRowAnimationFade];
} else if (editingStyle == UITableViewCellEditingStyleInsert) {
// Create a new instance of the appropriate class, insert it into the array, and add a new row to the table view.
}
}
/*
// Override to support rearranging the table view.
- (void)tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)fromIndexPath toIndexPath:(NSIndexPath *)toIndexPath
{
}
*/
/*
// Override to support conditional rearranging of the table view.
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
// Return NO if you do not want the item to be re-orderable.
return YES;
}
*/
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
if (!self.detailViewController) {
self.detailViewController = [[DetailViewController alloc] initWithNibName:#"DetailViewController" bundle:nil];
}
NSDate *object = [_objects objectAtIndex:indexPath.row];
self.detailViewController.detailItem = object;
[self.navigationController pushViewController:self.detailViewController animated:YES];
}
- (void)applicationWillResignActive:(NSNotification *)notification {
[_objects writeToFile:[self dataFilePath] atomically:YES];
}
#end
Most likely the cause of the error is that this returns 0:
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return ...;
}
I would suggest that you first take a complete working example of table view with all its required methods and start from there.
Generally you need to implement these methods:
(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
(NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section
(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
So far there is no issue with any NSMutableArray, anyway you cannot insert an object at an index if the array does not yet have the number of objects, eg insert at index 4 but the array has only 2 objects. You can always add objects to NSMutableArray and increase the number of objects in this array.
I have a table view that you can add and delete cells. I can enter multiple cells and when i go to the next page and then switch back, all of my entries/ cells are erased. Can any one figure this out? Here is my code:
#implementation FacePlatesViewController
#synthesize woodGrain;
#synthesize nav, array;
#synthesize EditButton;
#synthesize myTableView, image;
#synthesize cell, string1;
#synthesize myDic, cells, defaults;
#synthesize selectedCell, currentChosenFund;
- (void)viewDidLoad {
[super viewDidLoad];
NSString * myFile = [[NSBundle mainBundle]pathForResource:#"cells" ofType:#"plist"];
self.myTableView.backgroundColor = [UIColor clearColor];
cells = [[NSMutableArray alloc]initWithContentsOfFile:myFile];
}
- (void)addObject:(id)anObject
{
if (anObject != nil)
{
[cells addObject:anObject];
}
}
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
[self.myTableView reloadData];
}
- (IBAction)editButton:(id)sender
{
if (self.editing)
{
[self setEditing:NO animated:YES];
[self.myTableView setEditing:NO animated:YES];
}
else
{
[self setEditing:YES animated:YES];
[self.myTableView setEditing:YES animated:YES];
}
}
- (void)add
{
MyDetailViewController * detail = [[MyDetailViewController alloc]init];
detail.modalTransitionStyle = UIModalTransitionStyleCoverVertical;
[self presentModalViewController:detail animated:YES];
[detail.text becomeFirstResponder];
[detail release];
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
return [cells count];
}
- (void) tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle
forRowAtIndexPath:(NSIndexPath *)indexPath
{
if (editingStyle == UITableViewCellEditingStyleDelete)
{
[[self cells] removeObjectAtIndex:[indexPath row]];
NSArray *indexPaths = [NSArray arrayWithObject:indexPath];
[[self myTableView] deleteRowsAtIndexPaths:indexPaths
withRowAnimation:UITableViewRowAnimationFade];
}
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:
(NSIndexPath *)indexPath
{
static NSString *CellIdentifier = #"Cell";
cell = [tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil)
{
cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero
reuseIdentifier:CellIdentifier] autorelease];
}
//The if block should end here. You should set the cell's label irrespective whether the cell was nil. This is the cause of the issue you are facing.
cell.textLabel.text = [[cells objectAtIndex:indexPath.row] valueForKey:#"name"];
return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FirstFolderViewController * first = [[FirstFolderViewController alloc]init];
first.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:first animated:YES];
[first release];
}
- (BOOL)tableView:(UITableView *)tableView canMoveRowAtIndexPath:(NSIndexPath *)indexPath
{
return YES;
}
- (void) tableView:(UITableView *)tableView moveRowAtIndexPath:(NSIndexPath *)sourceIndexPath
toIndexPath:(NSIndexPath *)targetIndexPath
{
NSUInteger sourceIndex = [sourceIndexPath row];
NSUInteger targetIndex = [targetIndexPath row];
if (sourceIndex != targetIndex)
{
[[self cells] exchangeObjectAtIndex:sourceIndex
withObjectAtIndex:targetIndex];
}
}
- (void)dealloc
{
[woodGrain release];
[myTableView release];
[EditButton release];
[nav release];
[cells release];
[myTableView release];
[myDic release];
[super dealloc];
}
- (void)didReceiveMemoryWarning
{
[super didReceiveMemoryWarning];
}
#pragma mark - View lifecycle
/*
// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad
{
[super viewDidLoad];
}
*/
- (void)viewDidUnload
{
[self setWoodGrain: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 (interfaceOrientation == UIInterfaceOrientationPortrait);
}
#end
Thanks :D
Actually even unloading of the view will be enough to throw away the cells. Try this in your viewDidLoad:
if(!cells) {
NSString * myFile = [[NSBundle mainBundle]pathForResource:#"cells" ofType:#"plist"];
self.myTableView.backgroundColor = [UIColor clearColor];
cells = [[NSMutableArray alloc]initWithContentsOfFile:myFile];
}
(this way you won't be rereading the array every time the view is loaded).
And if you want the added cells to persist between app restarts, you do need to save them somewhere. You can't change the files in the main bundle, but you can write your own file into the Caches folder, which you can get via:
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
Write your file into that folder and read the cells from there instead of the main bundle. If you have some pre-defined cells in the main bundle file, you can check if the file in the Caches folder exists when the app starts, and if not, copy the bundle's file into the Caches folder.
Edit: if you do presentModalViewController to get back from the another page, you'll get a fresh copy of FacePlatesViewController, which obviously loads the default cells from the file.
Instead, you should add a "delegate" property to your FirstFolderViewController:
#property(nonatomic, assign) id delegate; //yes, assign, not retain
then when presenting FirstFolderViewController do:
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
FirstFolderViewController * first = [[FirstFolderViewController alloc]init];
first.delegate = self;
first.modalTransitionStyle = UIModalTransitionStyleFlipHorizontal;
[self presentModalViewController:first animated:YES];
[first release];
}
Then add a method to FacePlatesViewController:
- (void) onDoneWithFirstFolderViewController //you can come up with a better name
{
[self dismissModalViewControllerAnimated:YES];
}
and in your FirstFolderViewController, when you are ready to close it, do:
if([delegate respondsToSelector:#selector(onDoneWithFirstFolderViewController)])
[delegate onDoneWithFirstFolderViewController];
Ironically, if you had implemented the cell persistence in a file, this issue might have been unnoticed (because each new FacePlatesViewController would load an up-to-date cell list), but you would have had a memory leak each time you went between pages.
To me, the problem seems to be related to your code in ViewWillAppear: Have you ensured that your cells array is fine when you call [self.myTableView reloadData]; ?
Also, I noticed myTableView. Are you subclassing UITableViewController or implementing table delegates? If you are subclassing, the table view reference is named tableView.
HTH,
Akshay