ios - How get the total sum of float from a NSMutableArray

与世无争的帅哥 提交于 2019-12-20 06:03:12

问题


I created a NSMutableArray which contains a lot of NSString and float

DataOrder *addClient = [[DataOrder alloc ] initWithName:[[DataOrder instance]product] price:[[DataOrder instance]price] taille:[[DataOrder instance]taille] suplement:[[DataOrder instance]suplement]];    
[[[ArrayBuying instance] tableau]addObject:addClient];

I add the object in my array "[[ArrayBuying instance] tableau]"

How can I get the total sum of the float variables ?

Thank you


回答1:


Something like this will work:

float total = 0;
for (DataOrder *client in [[ArrayBuying instance] tableau]) {
    total += client.price;
}

NSLog(@"total = %f", total);

I'm just guessing that your DataOrder class has a price property. Use what you really have.




回答2:


Key-Value coding:

NSNumber *sum = [[[ArrayBuying instance] tableau] valueForKeyPath:@"@sum.price"];

gives the sum of the "price" attribute of all the objects in the array.

To make this work with your custom objects, price should be a property of DataOrder.




回答3:


Also if you didn't create any property/attribute, you can do like:

NSNumber *sum = [anArray valueForKeyPath:@"@sum.floatValue"];

or

float sum = [[anArray valueForKeyPath:@"@sum.floatValue"] floatValue];


来源:https://stackoverflow.com/questions/19938053/ios-how-get-the-total-sum-of-float-from-a-nsmutablearray

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