-1

I've created an Entity with attribute price with type NSDecimal. I try to count the sum of all prices in the entity:

@property(nonatomic,strong)NSArray *coisArr;
@property(nonatomic,strong)NSDecimalNumber *sum;


_sum =[_coisArr valueForKeyPath:@"price.floatValue"];
NSLog(@"Result: %@",_sum);

The result NSlog returns me:

 Result: (
"0.56",
"0.85",
1,
1,
12
)

Do I really get the sum? I try to show the result in a UILabel

NSNumberFormatter * formatter = [[NSNumberFormatter alloc] init];
[formatter setNumberStyle: NSNumberFormatterCurrencyStyle];
_lblTotalValue.text = [formatter stringFromNumber: _sum];

but get it empty. So where I went actually wrong?

NCFUSN
  • 1,624
  • 4
  • 28
  • 44
  • 3
    There is nothing in your code that actually asks for a sum, so it is hard to see why you expect there to be any sum anywhere. It's true that you named a instance variable `_sum` but that's irrelevant; names have no magic associated with them. Plus you are heading for a crash because you have assigned an NSArray to a variable declared as NSDecimalNumber. – matt May 28 '14 at 18:19
  • Plus you have recklessly declared your variable an NSDecimalNumber even though, even if you _did_ have the sum, it would not be an NSDecimalNumber (it would be a float). - You might like to read the docs. Carefully. https://developer.apple.com/library/ios/documentation/cocoa/conceptual/KeyValueCoding/Articles/CollectionOperators.html – matt May 28 '14 at 18:22
  • @matt `valueForKeyPath:` always returns an object type, so it wouldn't be a float. The `.floatValue` is meaningless in this case. – David Berry May 28 '14 at 19:19
  • @David You're absolutely right - I was typing too fast (and it's too late to edit it now): it's a float wrapped in an NSNumber. But in any case it will not arrive as an NSDecimalNumber and it is hard to see why he has declared this or his `price` attributes as NSDecimalNumber. – matt May 28 '14 at 20:19

1 Answers1

1

I think what you're looking for is:

_sum = [_coisArr valueForKeyPath:@"@sum.price"];

But your question is kind of unclear.

David Berry
  • 40,941
  • 12
  • 84
  • 95
  • http://stackoverflow.com/questions/6889646/calculating-a-simple-sum-with-core-data – sudo May 28 '14 at 19:26
  • @YoshiTheCorgi not sure what the reference is about. The "think" part of my answer is the vagueness of the question. – David Berry May 28 '14 at 19:31