Convert NSNumber to int in Objective-C - objective-c

I use [NSNumber numberWithInt:42] or #(42) to convert an int to NSNumber before adding it to an NSDictionary:
int intValue = 42;
NSNumber *numberValue = [NSNumber numberWithInt:intValue];
NSDictionary *dict = #{ #"integer" : numberValue };
When I retrieve the value from the NSDictionary, how can I transform it from NSNumber back to int?
NSNumber *number = dict[#"integer"];
int *intNumber = // ...?
It throws an exception saying casting is required when I do it this way:
int number = (int)dict[#"integer"];

Have a look at the documentation. Use the intValue method:
NSNumber *number = [dict objectForKey:#"integer"];
int intValue = [number intValue];

You should stick to the NSInteger data types when possible. So you'd create the number like that:
NSInteger myValue = 1;
NSNumber *number = [NSNumber numberWithInteger: myValue];
Decoding works with the integerValue method then:
NSInteger value = [number integerValue];

Use the NSNumber method intValue
Here is Apple reference documentation

A tested one-liner:
int number = ((NSNumber*)[dict objectForKey:#"integer"]).intValue;

A less verbose approach:
int number = [dict[#"integer"] intValue];

Related

How to get result?

hello! Sorry for my question. I hope you'll ask and help me.
I want to get result with this code:
NSNumber *first = #10;
NSNumber *second = #30;
NSNumber *resultTest = first + second;
But Xcode got a error, unfortunately. How to add the variables with class NSNumber?
I know I can with this way:
int first = 10;
int second = 20;
int result = first + second;
But how to do it with class NSNumber?
Sorry again. I am newbie in Objective-C programming. Thank you.
You can convert NSNumber to int, sum the numbers, then convert back to NSNumber.
NSNumber *result = [NSNumber numberWithInt:([first intValue] + [second intValue])];
NSNumber isn't designed to be used in calculations. It's main usage is to wrap primitive (numeric) types so that they can be used in contexts where you need an object---typically for storing them in a collection such as an NSArray.
That being said, the following will work:
NSNumber *first = #10;
NSNumber *second = #30;
NSNumber *third = #([first integerValue] + [second integerValue]);

Add two NSStrings together (numbers)

im trying this:
NSNumber *num1;
NSNumber *num2;
self.addNumberOfRoundsText.text = [num1 stringValue];
self.numberOfRoundsText.text = [num2 stringValue];
NSNumber *sum = [NSNumber numberWithInt:([num1 intValue] + [num2 intValue])];
NSLog(#"%#", [sum stringValue]);
For some reason, the console keeps outputting 0 im not sure if there is something i am missing. I just want to get the text from two UITextField's and add them. Then output them to the console. Thank you for the help!
In your example code, you haven't initialized num1 and num2. So (if you are using ARC, which is the default for new projects), those variables are initialized to nil.
In Objective-C, you can send any message (like stringValue or intValue) to nil, and it will return 0 or nil back. So:
NSNumber *num1; // initialized to nil by ARC
NSNumber *num2; // initialized to nil by ARC
// This sets self.addNumberOfRoundsText.text to nil.
self.addNumberOfRoundsText.text = [num1 stringValue];
// This sets self.numberOfRoundsText.text to nil.
self.numberOfRoundsText.text = [num2 stringValue];
// This gets 0 for [num1 intValue] and 0 for [num2 intValue], which add up
// to 0, so sum is an NSNumber representing zero.
NSNumber *sum = [NSNumber numberWithInt:([num1 intValue] + [num2 intValue])];
NSLog(#"%#", [sum stringValue]);
I'm not sure what you're actually trying to do. Maybe you have two text fields, and each text field contains a number, and you want to add up those two numbers. If that's what you want to do, try this:
int n1 = self.addNumberOfRoundsText.text.intValue;
int n2 = self.numberOfRoundsText.text.intValue;
int sum = n1 + n2;
NSLog(#"sum = %d", sum);
Here is the Code as you asked you want to add two UITextField Value into one single String
NSString* finalSTring;
finalSTring =[NSString stringWithFormat:#"%#%#",textfield1.text,textField2.text];
//textField1 and Textfield2 is instance of TextField.
NSLog(#"%#",finalSTring);//here you have new Single String
If you have two text fields: field1 and field2:
int sum = [field1.text intValue] + [field2.text intValue];
Or if you want sum as an NSNumber:
NSNumber* sum = [NSNumber numberWithInt:[field1.text intValue] + [field2.text intValue]];
why not to set it like this
NSNumber *num1;
NSNumber *num2;
self.addNumberOfRoundsText.text = [NSString stringWithFormat:#"%#",num1];
self.numberOfRoundsText.text = [NSString stringWithFormat:#"%#",num2];
NSNumber *sum = num1 + num2 ;
NSLog(#"%#", sum );

Assigning an arrays count to an int, NSNumber or NSUInteger fails

Assigning an int, NSNumber and NSUInteger to an arrays count fails...
this is my line of code
int diamondCount = [diamonds count];
where diamonds is an nsarray
I built the app and it threw an EXC_BAD_ACESS on that line
So i looked at the NSArray count method and found it returns an nsuinteger
So i did:
NSUInteger diamondCount = [diamonds count];
that still threw me EXC_BAD_ACCESS so at last resort i assigned it to an nsnumber with numberWithInteger:
it stilled crashed.... any thoughts?
diamonds does not point to a real (and valid) NSArray. Check its initialization.
Try this:
NSArray *myArray;
NSDate *aDate = [NSDate distantFuture];
NSValue *aValue = [NSNumber numberWithInt:5];
NSString *aString = #"a string";
myArray = [NSArray arrayWithObjects:aDate, aValue, aString, nil];
int i = [myArray count];
NSLog(#"%d",i);
NSInteger j = [myArray count];
NSLog(#"%d",j);
NSNumber *k = [myArray count];
NSLog(#"%d",k);
/*output
2011-11-21 17:01:48.272 test[48840:1303] 3
2011-11-21 17:01:48.272 test[48840:1303] 3
2011-11-21 17:01:48.273 test[48840:1303] 3*/

how to add int value from array to NSNumber?

Here is my code
I'm looping through the array and adding to the NSNumber.
NSNumber *totalValue = 0;
NSMutableArray *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];

Add up all values from NSMutableArray

I have a NSMutableArray, containing x different NSStrings (NSString but only numbers no letters). I would like to add up all of the values to return a single float, or int. I think I have to do this with a for loop, but i am very unfamiliar with for loops....
OK I have reached this point:
for (NSString *a in det)
{
float x = [a floatValue];
NSLog(#"%.2f",x);
}
And this returns all the values like this in ´NSLog`:
23.00
8.00
61.00
...
How could i just add them up now?
You can avoid looping and instead use the key value coding and obtain the total
NSMutableArray *arr = [NSMutableArray arrayWithObjects:#"1.1", #"2.2", #"3.1", nil];
NSNumber *sum = [arr valueForKeyPath:#"#sum.floatValue"];
Variable sum will be 6.4.
Try this:
float total = 0;
for(NSString *str in det)
{
total += [str floatValue];
}
Here is the code for a for-in if you want to save a bit of typing. It's preferable to use fast enumeration for these types of scenarios with data structures that support it.
float result = 0.0;
for(NSString *i in nsArray)
{
result += [i floatValue];
}
int result = 0;
for(int i=0;i<[array count];i++)
result += [[array objectAtIndex:i] intValue];
if you need to return a float simply define result as float and use floatValue instead of intValue