How can summarize all numbers in NSArray?

时间:2018-08-22 13:53:47

标签: nsdate

I have NSArray with strings - 00:02:34, 02:05:17 so i need to calculate all strings in my array and get result: 2 hours:7 minutes and 51 seconds.

I tried this:

// Get strings from array for the first and separate for three objects by:

for (NSDictionary *dic in dicts) {
      NSString *string = dic[@"duration"]; (my type of string 00:00:00)
       NSArray *components = [string componentsSeparatedByString:@":"];
        NSInteger minutes  = [components[1] integerValue];
        NSInteger seconds  = [components[2] integerValue];
        NSInteger hour     = [components[0] integerValue];
}

But how can i summ this date to get results? Thanks for help.

1 个答案:

答案 0 :(得分:0)

有几种方法可以解决这个问题。

我个人将遍历dicts,并将每个duration字符串转换为 seconds ,并将总秒数保持为循环外的整数。

然后,在循环完成后,您可以轻松地将累计的总秒数转换回小时,分钟和秒,并从中组成一个字符串:

int totalSeconds = 0;
for (NSDictionary * dic in dicts) {
    NSString *string = dic[@"duration"];
    NSArray *components = [string componentsSeparatedByString:@":"];
    totalSeconds += (int) [components[0] integerValue] * 60 * 60;
    totalSeconds += (int) [components[1] integerValue] * 60;
    totalSeconds += (int) [components[2] integerValue];
}

int hour = totalSeconds / 3600;
int mins = (totalSeconds % 3600) / 60;
int secs = totalSeconds % 60;
NSString * totalString = [NSString stringWithFormat:@"%d:%d:%d", hour, mins, secs];

注意:您必须编写一些代码来组成字符串,并在其中任何值小于10的情况下酌情包括零。