1

我喜欢做什么:

  • 用户输入 10UITextField并点击UIButton
  • UILabel显示 10 并UITextField变为空白。
  • 用户输入 5UITextField并点击UIButton
  • UILable显示 15 并UITextField再次变为空白。

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

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

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

2 回答 2

0

遍历数组,将所有值作为数字使用[string intValue]并将它们汇总到另一个变量中。然后使用格式化字符串(如[NSString stringWithFormat: @"%d"].

于 2012-04-19T15:00:42.410 回答
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];
}

我已经评论了代码的可读性。

于 2012-04-19T15:08:04.487 回答