3

My NSMutableArray is declared in my .h file like this

@property (strong, nonatomic) NSMutableArray * numbers;

How do I use the NSMutableArray to save the data that is inputed to save to NSUserDefaults

All help is appreciated

Thanks in advance

code in .h file

@property (retain, nonatomic) IBOutlet UITableView *myTableView;
@property (strong, nonatomic) NSMutableArray * numbers;

code in .m

@synthesize myTableView, numbers;

-(void) viewDidLoad
{

    NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
    [defaults setObject:numbers forKey:@"numberArray"];

    NSMutableArray *resultArray = [NSMutableArray arrayWithArray:[defaults objectForKey:@"numberArray"]];



    [super viewDidLoad];
    // instantiate our NSMutableArray
    numbers = [[NSMutableArray alloc]initWithObjects:@"",@"", nil];






    //Add a edit button
    self.navigationItem.leftBarButtonItem = self.editButtonItem;

    //Add the Add button
    UIBarButtonItem * addButton = [[UIBarButtonItem alloc]
                                   initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target: self action: @selector(insertNewObject)];

    self.navigationItem.rightBarButtonItem = addButton;

}
-(void) didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];

}

-(void)setEditing:(BOOL)editing animated:(BOOL)animated
{

    [super setEditing:editing animated:animated];
    [myTableView setEditing:editing animated:animated];




}


-(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];

}



#pragma mark - UITableView Datasource

-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 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 = [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
        [numbers removeObjectAtIndex:indexPath.row];
        //remove from our tableView
        [tableView deleteRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    }


}


#pragma mark - UITableView Delegate methods


#pragma mark - UIAlertViewDelegate Methods


-(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(!numbers)

            numbers = [[NSMutableArray alloc]init];




    [numbers insertObject:tmpTextField atIndex:0];



        NSIndexPath * indexPath = [NSIndexPath indexPathForRow:0 inSection:0];

        [self.myTableView insertRowsAtIndexPaths:@[indexPath]withRowAnimation:UITableViewRowAnimationAutomatic];



        }



}


@end

Ok, in my app, there is a UITableView

when the user taps the "plus" button, a UIAlertView shows up with a UITextField, when the user types a word, the text goes to the UITableView, but when the user exits the app, the text is gone from the table. I want to save the text the user puts in, so when the user exits the app and comes back, i want the text to save. I want to save it with NSUserDefaults.

HpTerm
  • 8,151
  • 12
  • 51
  • 67
user2167312
  • 129
  • 1
  • 2
  • 6

1 Answers1

16
//For saving 
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
[defaults setObject:self.numbers forKey:@"numberArray"];
[defaults synchronize];

//For retrieving  
NSMutableArray *resultArray = [NSMutableArray arrayWithArray:[defaults objectForKey:@"numberArray"]];

According to you scenario when you running application after exiting... you should in viewDidLoad check if the keyExists in the NSUserDefaults then retrieve the results in the array and show in the UITableView. For Saving the Data, it is good idea to listen to a notification when user minimize the app, just save the data into the defaults.

Here is the working code for your case

- (void)viewDidLoad{

   [super viewDidLoad];
// Do any additional setup after loading the view, typically from a nib.

    //Add a edit button
   self.navigationController.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.navigationController.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];
        }


}
nsgulliver
  • 12,655
  • 23
  • 43
  • 64
  • 4
    Thank you for correctly making a new mutable array, rather than assuming that the original mutable array would still be mutable when you get it back :) – Catfish_Man Mar 13 '13 at 21:04
  • do I put this in the .m file, anywhere? – user2167312 Mar 13 '13 at 21:15
  • the user taps the plus button and types in some text and gets added to a table view, I used the NSMutableArray to identify the text. How i save that – user2167312 Mar 13 '13 at 21:27
  • you want to add data in the array first? this is what you want? – nsgulliver Mar 13 '13 at 21:30
  • when i close and open the app, the text is gone, that i typed in earlier – user2167312 Mar 13 '13 at 21:31
  • nsgulliver, yes i want to add data to the array first – user2167312 Mar 13 '13 at 21:32
  • that is why presented code above helps you to save data in defaults so that you can retrieve it again and use in your tableView – nsgulliver Mar 13 '13 at 21:32
  • the code above didnt work, it doesnt show the text when i leave the application. – user2167312 Mar 13 '13 at 21:35
  • Code is correct, nothing wrong in code, you should see first if you are adding anything inside the array. – nsgulliver Mar 13 '13 at 21:35
  • You are just putting an empty array in the defaults, how would you expect to have data from defaults if you did not save anything in it? first add something in the array and then save it. – nsgulliver Mar 13 '13 at 21:43
  • but i want the text that the user adds, to save – user2167312 Mar 13 '13 at 21:45
  • save to the defaults after you adding something inside the numbers array, I see you add data in numbers array in `-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex` method, you could save the array after you filled up in this method – nsgulliver Mar 13 '13 at 21:46
  • I put the save code in the place u told me to put it in. An error on xcode showed and said that *resultArray is a unused variable – user2167312 Mar 13 '13 at 21:49
  • if you were doing this and wanted to save the text, wat code would you put where, exact code. Please help me – user2167312 Mar 13 '13 at 21:52
  • resultArray is unused array because you did not use it, you can try to print out the results of resultArray by putting in `NSLog(@"results from defaults%@",resultArray);` – nsgulliver Mar 13 '13 at 21:55
  • just save the array when you are done adding date into it, and don't forget to `[defaults synchronize];` as i mentioned in the code – nsgulliver Mar 13 '13 at 22:24
  • it is warning, if you are not using the data then no need to worry about that, but as I said you should print out the resultArray so you know what it contains – nsgulliver Mar 13 '13 at 22:43
  • @user2167312 I hope you solve your problem, if you copy and paste the code above – nsgulliver Mar 13 '13 at 23:11
  • @user2167312 you can use notification to save the data, this way you will avoid saving data all the time when user clicks on ok button of AlertView, check out my updated answer, it is working code just use it – nsgulliver Mar 13 '13 at 23:28
  • THANK YOU VERY MUCH nsgulliver IT WORKED, THANK YOU, I HIGHLY APPRECIATE YOUR HELP! – user2167312 Mar 14 '13 at 01:36