将几个整数保存到数组并在标签中显示总值

时间:2012-04-19 14:49:01

标签: iphone objective-c nsmutablearray nsfilemanager

我喜欢做什么:

  • 用户在UITextField中输入10,然后点按UIButton
  • UILabel显示10,UITextField显示为空白。
  • 用户在UITextField中输入5,然后点按UIButton
  • UILable显示15,UITextField再次显示为空白。

使用以下代码,我将保存输入的数字并显示在标签中,但是如何告诉数组添加并显示总数而不仅仅是我输入的第一个数字?

ħ

#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

#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]];
}

2 个答案:

答案 0 :(得分:0)

迭代数组,使用[string intValue]将所有值作为数字,并在另一个变量中求和。然后使用格式化的字符串[NSString stringWithFormat: @"%d"]将计算值添加到标签中。

答案 1 :(得分:0)

您需要遍历所有值并将其添加到运行总计中。看看这个: -

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

我评论了代码的可读性。