Search code examples
iphoneobjective-cnsmutablearraynsfilemanager

Save several ints to array and show total value in a label


What I like to do:

  • User enters 10 in UITextField and tap on UIButton.
  • UILabel shows 10 and UITextField goes blank.
  • User enters 5 in UITextField and tap on UIButton.
  • UILable shows 15 and UITextField goes blank again.

With following code I get the entered number saved and shown in the label but how can I tell the array to add and show me total and not just the very first number I entered?

h

#import <UIKit/UIKit.h>

@interface ViewController : UIViewController

@property (nonatomic, strong) IBOutlet UILabel *label;
@property (nonatomic, strong) IBOutlet UITextField *field;

@property (nonatomic, strong) NSString *dataFilePath;
@property (nonatomic, strong) NSString *docsDir;
@property (nonatomic, strong) NSArray *dirPaths;

@property (nonatomic, strong) NSFileManager *fileMgr;
@property (nonatomic, strong) NSMutableArray *array;

- (IBAction)saveNumber:(id)sender;

@end

m

#import "ViewController.h"

@interface ViewController ()

@end

@implementation ViewController
@synthesize label, field, dataFilePath, docsDir, fileMgr, dirPaths, array;

- (void)viewDidLoad
{
    [super viewDidLoad];

    fileMgr = [NSFileManager defaultManager];
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];
    dataFilePath = [[NSString alloc]initWithString:[docsDir stringByAppendingPathComponent:@"data.archive"]];

    if ([fileMgr fileExistsAtPath:dataFilePath])
    {
       array = [NSKeyedUnarchiver unarchiveObjectWithFile:dataFilePath];
        self.label.text = [array objectAtIndex:0];
    }
    else 
    {
        array = [[NSMutableArray alloc] init];
    }

}


- (IBAction)saveNumber:(id)sender
{
    [array addObject:self.field.text];
    [NSKeyedArchiver archiveRootObject:array toFile:dataFilePath];
    [field setText:@""];
    [label setText:[array objectAtIndex:0]];
}

Solution

  • You need to iterate through all the values and add them to a running total. Have a look at this:-

     - (IBAction)saveNumber:(id)sender
    {
        [array addObject:self.field.text];
        [NSKeyedArchiver archiveRootObject:array toFile:dataFilePath];
        [field setText:@""];
    
        // Create an enumerator from the array to easily iterate
        NSEnumerator *e = [array objectEnumerator];
    
        // Create a running total and temp string
        int total = 0;
        NSString stringNumber;
    
        // Enumerate through all elements of the array
        while (stringNumber = [e nextObject]) {
            // Add current number to the running total
            total += [stringNumber intValue];
        }
    
        // Now set the label to the total of all numbers
        [label setText:[NSString stringWithFormat:@"%d",total];
    }
    

    I've commented the code for readability.