I think tableData
is getting deallocated when you are coming back to the home page. If the tableData
is not a huge array you can store it in NSUserDefaults
. This way when ever you come back to the table you can always retreat the data. Check out this code. It will store the tableData
in the NSUserDefaults every time you add anything to the array. Let me know if this works for you.
#import "ViewController.h"
@interface ViewController () <UIAlertViewDelegate,UITableViewDataSource,UITableViewDelegate>
@property (weak, nonatomic) IBOutlet UITableView *myTableView;
@property (nonatomic,strong) NSMutableArray *tableData;
@end
@implementation ViewController
-(NSMutableArray *)tableData
{
if(!_tableData){
NSMutableArray *data = [[NSUserDefaults standardUserDefaults]objectForKey:@"data"];
if(!data){
_tableData = [[NSMutableArray alloc]init];
}else{
_tableData = [data mutableCopy];
}
}
return _tableData;
}
- (IBAction)add:(UIButton *)sender {
UIAlertView* alert=[[UIAlertView alloc] initWithTitle:@"My Favs" message:@"Hello" delegate:self cancelButtonTitle:@"Cancel" otherButtonTitles:@"Save", nil];
alert.alertViewStyle = UIAlertViewStylePlainTextInput;
UITextField * alertTextField = [alert textFieldAtIndex:0];
alertTextField.enablesReturnKeyAutomatically = YES;
alertTextField.placeholder = @"example";
[alert show];
}
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
if (buttonIndex == 1){
NSString *tapTextField = [alertView textFieldAtIndex:0].text;
[self.tableData insertObject:tapTextField atIndex:0];
NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:self.tableData forKey:@"data"];
[defaults synchronize];
[self.myTableView reloadData];
}
}
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
return[self.tableData count];
}
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
return 1;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"dataCell" forIndexPath:indexPath];
if(self.tableData.count > 0){
cell.textLabel.text = self.tableData[indexPath.row];
}
return cell;
}