How get the total sum of NSNumber's from a NSArray?

杀马特。学长 韩版系。学妹 提交于 2019-12-09 07:41:34

问题


I have a large NSArray containing NSNumbers like 3, 4, 20, 10, 1, 100, etc...

How do I get the total sum of all these NSNumbers (3 + 4 + 20 + 10 + 1 + 100 + etc...) as one total NSInteger?

Thank you!


回答1:


NSInteger sum = 0;
for (NSNumber *num in myArray) {
  sum += [num intValue];
}



回答2:


You can use this:

NSArray* numbers = //array of numbers
NSNumber* sum = [numbers valueForKeyPath: @"@sum.self"];



回答3:


long long sum = ((NSNumber*)[array valueForKeyPath: @"@sum.longLongValue"]).longLongValue;



回答4:


Iterate through the array

int count = [array count];
NSInteger sum = 0;
for (int i = 0; i < count; i++) {
    sum += [[array objectAtIndex:i] integerValue];
}



回答5:


[[numbersArray valueForKeyPath:@"@sum.self"] integerValue]



回答6:


int total = 0;
for (NSNumber *number in array)
{
  total += [number intValue];
}

may this will help you



来源:https://stackoverflow.com/questions/11192503/how-get-the-total-sum-of-nsnumbers-from-a-nsarray

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!