What I like to do:
- User enters 10 in
UITextFieldand tap onUIButton. UILabelshows 10 andUITextFieldgoes blank.- User enters 5 in
UITextFieldand tap onUIButton. UILableshows 15 andUITextFieldgoes 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]];
}
You need to iterate through all the values and add them to a running total. Have a look at this:-
I’ve commented the code for readability.