开发者

how to add int value from array to NSNumber?

开发者 https://www.devze.com 2023-04-12 18:52 出处:网络
Here is my code I\'m looping through the array and adding to the NSNumber. NSNumber *totalValue = 0; NSMutableArra开发者_如何转开发y *items = [10, 35, 25]; // Just for demo

Here is my code

I'm looping through the array and adding to the NSNumber.

NSNumber *totalValue = 0; 
NSMutableArra开发者_如何转开发y *items = [10, 35, 25]; // Just for demo
for (int i=0; i < items.count; i++)
{
    totalValue = totalValue + [items objectAtIndex:i] // How do I add the totalValue?
}

Can someone help me with this code?


NSNumber is an Objective-C class. Unlike in C++, operators cannot be overloaded in Objective-C so you have to call everything manually.

NSNumber *totalValue = [NSNumber numberWithInt:0];
for(…) {
  totalValue = [NSNumber numberWithInt:[totalValue intValue] + [[items objectAtIndex:i] intValue]];
}

You might want to use NSInteger instead, which is faster (especially for a large number of items: memory allocation is expensive):

NSInteger totalValueInteger = 0; // no pointer, NSInteger is a POD!
for (…) {
  totalValueInteger += [[items objectAtIndex:i] integerValue];
}
NSNumber *totalValue = [NSNumber numberWithInteger:totalValueInteger];

You should really only use NSNumber when you need an Objective-C object, like in an array, dictionary or coder. Otherwise, use a POD like NSInteger, int or double.


First of all, you can probably do this entire thing using KVC:

NSNumber *total = [items valueForKeyPath:@"@sum.integerValue"];

But to answer your original question, NSNumber is immutable which means you can't change it or increment its value. Creating a new NSNumber on each iteration of your loop is inefficient and wasteful.

You should use a standard int or NSInteger to sum up the total, and then convert the resulting value to an NSNumber at the end if you need it like that.


Might as well make the intermediate an int.

int temp = 0;
for(…) {
  temp += [[items objectAtIndex:i] intValue];
}
NSNumber *totalValue = [NSNumber numberWithInt:temp];
0

精彩评论

暂无评论...
验证码 换一张
取 消