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 );
Related
- (void)updateCheckBoxes {
NSArray *availableFuncUnits = _scanner.availableFunctionalUnitTypes;
for(int i = 0; i < [availableFuncUnits count]; i++) {
}
}
If I put a breakpoint inside the for loop, the elements of the NSArray * 'availableFuncUnits' are (__NSCFNumber *)(int)0 and (__NSCFNumber *)(long)3.
The array is supposed to contain elements of the following :
enum
{
ICScannerFunctionalUnitTypeFlatbed = 0,
ICScannerFunctionalUnitTypePositiveTransparency = 1,
ICScannerFunctionalUnitTypeNegativeTransparency = 2,
ICScannerFunctionalUnitTypeDocumentFeeder = 3
};
typedef NSUInteger ICScannerFunctionalUnitType;
Shouldn't I be able to do the following?
if([availableFuncUnits objectAtIndex:i] == ICScannerFunctionalUnitType.ICScannerFunctionalUnitTypeDocumentFeeder) {}
But it always gives me an error saying 'Expected identifier or '('.
How can I perform this comparison correctly? Thanks a lot for the help!
There are two problems that I see:
1) The array availableFuncUnits contains NSNumber objects. You cant directly compare them with primitive types (NSUInteger).
So your if should be like this:
ICScannerFunctionalUnitType type = [availableFuncUnits[i] integerValue]
if(type == ICScannerFunctionalUnitTypeDocumentFeeder){}
In your snippet you were comparing the pointer, not the object.
2) The error you were seeing is because the proper way to use enums is:
i = ICScannerFunctionalUnitTypeDocumentFeeder
You can't store integers in an NSArray because array's can only contain objects. To get integers into an array they must be wrapped with NSNumber:
NSInteger a = 100;
NSInteger b = 200;
NSInteger c = 300;
// Creating NSNumber objects the long way
NSArray *arrayOne = [NSArray alloc] initWithObjects:[NSNumber numberWithInteger:a],
[NSNumber numberWithInteger:b],
[NSNumber numberWithInteger:c], nil];
// Creating NSNumber objects the short way
NSArray *arrayTwo = [[NSArray alloc] initWithObjects:#100, #200, #300, nil];
This is relevant you your question because when you extract your NSNumber objects from your array, if you want to then compare them to actual integers, you must convert them back to integers (unwrap them).
NSLog(#"%d", [arrayOne firstObject] == 100); // COMPILER WARNING!!!
NSLog(#"%d", [[arrayOne firstObject] integerValue] == 100); // True
NSLog(#"%d", [[arrayTwo lastObject] integerValue] == 200); // False
This stage appears to be missing in your example.
Finally to compare your integer values with those from an enum, there's no need to reference the enum name, just use the individual values that make up the enum:
[[arrayTwo lastObject] integerValue] == ICScannerFunctionalUnitTypeFlatbed
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];
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]);
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 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