I am making a quiz app. Here is a part of my code:
-(void)getQuestion:(int)randomvalue{
if (Stufe == 1) {
iD = arc4random() % 50 + 1000;
}
if (Stufe == 2) {
iD = arc4random() % 56 + 2000;
}
if (Stufe == 3) {
iD = arc4random() % 52 + 3000;
}
NSString *Abfrage = [NSString stringWithFormat:#"SELECT frage FROM questions WHERE id = %d", iD];
I am working with sqlite3 and with the iD I got my question from my database. Now how can save the iD in a NSMutableArray and how I can check firstly whether the iD exists in my NSMutableArray? So that the App don't ask the same question. (Stufe is difficulty and unimportant).
Thanks
Conversion from int to NSNumber
iD is currently an int. You will need to convert it to an NSNumber object before it can be stored within an NSMutableArray. You can do this with numberWithInt.
NSNumber* iDNumber = [NSNumber numberWithInt:iD];
Creating an NSMutableArray containing the NSNumber
Once you have the NSNumber, you can create an NSMutableArray with arrayWithObjects.
NSMutableArray *iDArray = [NSMutableArray arrayWithObjects:iDNumber, nil];
Adding an NSNumber to an existing NSMutableArray
You can add the item to an existing NSMutableArray with addObject.
[iDArray addObject: iDNumber];
Checking if an NSNumber already exists in an NSMutableArray
To check if the array already contains the object, you can use containsObject.
if (![iDArray containsObject: iDNumber])
{
[iDArray addObject: iDNumber];
}
Conversion from NSNumber to int
If you want to use an NSNumber as an int later, you will need to convert it back using intValue.
int iDInt = [iDNumber intValue];
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 );
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];
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];
How can I convert a NSString containing a number of any primitive data type (e.g. int, float, char, unsigned int, etc.)? The problem is, I don't know which number type the string will contain at runtime.
I have an idea how to do it, but I'm not sure if this works with any type, also unsigned and floating point values:
long long scannedNumber;
NSScanner *scanner = [NSScanner scannerWithString:aString];
[scanner scanLongLong:&scannedNumber];
NSNumber *number = [NSNumber numberWithLongLong: scannedNumber];
Thanks for the help.
Use an NSNumberFormatter:
NSNumberFormatter *f = [[NSNumberFormatter alloc] init];
f.numberStyle = NSNumberFormatterDecimalStyle;
NSNumber *myNumber = [f numberFromString:#"42"];
If the string is not a valid number, then myNumber will be nil. If it is a valid number, then you now have all of the NSNumber goodness to figure out what kind of number it actually is.
You can use -[NSString integerValue], -[NSString floatValue], etc. However, the correct (locale-sensitive, etc.) way to do this is to use -[NSNumberFormatter numberFromString:] which will give you an NSNumber converted from the appropriate locale and given the settings of the NSNumberFormatter (including whether it will allow floating point values).
Objective-C
(Note: this method doesn't play nice with difference locales, but is slightly faster than a NSNumberFormatter)
NSNumber *num1 = #([#"42" intValue]);
NSNumber *num2 = #([#"42.42" floatValue]);
Swift
Simple but dirty way
// Swift 1.2
if let intValue = "42".toInt() {
let number1 = NSNumber(integer:intValue)
}
// Swift 2.0
let number2 = Int("42')
// Swift 3.0
NSDecimalNumber(string: "42.42")
// Using NSNumber
let number3 = NSNumber(float:("42.42" as NSString).floatValue)
The extension-way
This is better, really, because it'll play nicely with locales and decimals.
extension String {
var numberValue:NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
Now you can simply do:
let someFloat = "42.42".numberValue
let someInt = "42".numberValue
For strings starting with integers, e.g., #"123", #"456 ft", #"7.89", etc., use -[NSString integerValue].
So, #([#"12.8 lbs" integerValue]) is like doing [NSNumber numberWithInteger:12].
You can also do this:
NSNumber *number = #([dictionary[#"id"] intValue]]);
Have fun!
If you know that you receive integers, you could use:
NSString* val = #"12";
[NSNumber numberWithInt:[val intValue]];
Here's a working sample of NSNumberFormatter reading localized number NSString (xCode 3.2.4, osX 10.6), to save others the hours I've just spent messing around. Beware: while it can handle trailing blanks ("8,765.4 " works), this cannot handle leading white space and this cannot handle stray text characters. (Bad input strings: " 8" and "8q" and "8 q".)
NSString *tempStr = #"8,765.4";
// localization allows other thousands separators, also.
NSNumberFormatter * myNumFormatter = [[NSNumberFormatter alloc] init];
[myNumFormatter setLocale:[NSLocale currentLocale]]; // happen by default?
[myNumFormatter setFormatterBehavior:NSNumberFormatterBehavior10_4];
// next line is very important!
[myNumFormatter setNumberStyle:NSNumberFormatterDecimalStyle]; // crucial
NSNumber *tempNum = [myNumFormatter numberFromString:tempStr];
NSLog(#"string '%#' gives NSNumber '%#' with intValue '%i'",
tempStr, tempNum, [tempNum intValue]);
[myNumFormatter release]; // good citizen
I wanted to convert a string to a double. This above answer didn't quite work for me. But this did: How to do string conversions in Objective-C?
All I pretty much did was:
double myDouble = [myString doubleValue];
Thanks All! I am combined feedback and finally manage to convert from text input ( string ) to Integer. Plus it could tell me whether the input is integer :)
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterDecimalStyle];
NSNumber * myNumber = [f numberFromString:thresholdInput.text];
int minThreshold = [myNumber intValue];
NSLog(#"Setting for minThreshold %i", minThreshold);
if ((int)minThreshold < 1 )
{
NSLog(#"Not a number");
}
else
{
NSLog(#"Setting for integer minThreshold %i", minThreshold);
}
[f release];
I think NSDecimalNumber will do it:
Example:
NSNumber *theNumber = [NSDecimalNumber decimalNumberWithString:[stringVariable text]]];
NSDecimalNumber is a subclass of NSNumber, so implicit casting allowed.
What about C's standard atoi?
int num = atoi([scannedNumber cStringUsingEncoding:NSUTF8StringEncoding]);
Do you think there are any caveats?
You can just use [string intValue] or [string floatValue] or [string doubleValue] etc
You can also use NSNumberFormatter class:
you can also do like this code 8.3.3 ios 10.3 support
[NSNumber numberWithInt:[#"put your string here" intValue]]
NSDecimalNumber *myNumber = [NSDecimalNumber decimalNumberWithString:#"123.45"];
NSLog(#"My Number : %#",myNumber);
Try this
NSNumber *yourNumber = [NSNumber numberWithLongLong:[yourString longLongValue]];
Note - I have used longLongValue as per my requirement. You can also use integerValue, longValue, or any other format depending upon your requirement.
Worked in Swift 3
NSDecimalNumber(string: "Your string")
I know this is very late but below code is working for me.
Try this code
NSNumber *number = #([dictionary[#"keyValue"] intValue]]);
This may help you. Thanks
extension String {
var numberValue:NSNumber? {
let formatter = NumberFormatter()
formatter.numberStyle = .decimal
return formatter.number(from: self)
}
}
let someFloat = "12.34".numberValue