How to compare a NSNumber in an if - iphone

How to:
if (myNSNumber == 1)
{
...
}
This doesn't seem to build
The object:

If myNSNUmber is NSNumber, your code should read,
if ([myNSNumber intValue] == 1) {
...
}
If it is NSInteger, you can directly compare it with an integer literal. Because NSInteger is a primitive data type.
if (myNSNumber == 1) {
...
}
Note: Make sure you don't have * in your declaration. Your NSInteger declarations should read,
NSInteger myNSNUmber; // RIGHT
NSInteger *myNSNUmber; // WRONG, NSInteger is not a struct, but it is a primitive data type.
The following is based on #BoltClock's answer, which he recently posted here
However if you do need to use a pointer to an NSInteger (that is, NSInteger *) for some reason, then you need to dereference the pointer to get the value:
if (*myNSNUmber == 11) {
}

NSInteger is normally a plain int type so your code should work fine.
if myNSNumber a NSNumber object (as variable name suggests) then you should extract its int value:
if ([myNSNumber intValue] == 1)
{
...
}

Related

Condition always fails though the comparative values seems correct in iOS

When I check the value of number in nslog it shows '0'
NSMutableDictionary *data = [[NSMutableDictionary alloc] initWithContentsOfFile: path];
NSNumber *number=[data objectForKey:#"serial"];
NSLog(#"%#",number);
if(number ==0 )
{
imgButton.hidden=YES;
}
But the condition always fails , I also changed the code like this
NSString *number=[data objectForKey:#"serial"]
NSLog(#"%#",number);
if(number == #"0" )
{
imgButton.hidden=YES;
}
But here too the condition fail ,What is the issue with this?
In the first code you are checking a NSNumber, object, against an int.
The correct check is:
if([number intValue] == 0) {
imgButton.hidden = YES;
}
In the second code you are checking two NSString, but you have to use the "isEqualToString" method and not "==". The correct code is:
if([number isEqualToString:#"0"]) {
imgButton.hidden = YES;
}
NSNumber is an object, 0 is an integer (a primitive type). They will never be equal. But you can change the comparison like this [number intValue] == 0 and this will work when the value of your NSNumber is 0.
On the string comparison, you should use the method
isEqualToString:NSString *)string
for the comparison.
For NSNumbers its
isEqualToNumber:(NSNumber *)number
Because otherwise you arent comparing if they have the same value, but if they are stored in identical memory space.

Method to put NSString and NSNumber into array

It's a calculator. I have a display where I can put digits and variables (x, y etc.). When I push Enter button it sends what is on display to array with all operand.
As on display can be NSString (variables) or NSNumber (digits) I thought to use "id" as method argument.
- (IBAction)enterPressed
{
[self.brain pushOperand:self.display.text];
}
/////////////////////
- (void) pushOperand:(id)operand
{
////// So if operand is digit I need to transform it into NSNumber.
NSNumber *digitToStack = [NSNumber numberWithDouble:operand];
/////// Here is problem - "Sending '___strong id' to parameter of incompatible type 'double'
NSNumber *digitToStack = [operand doubleValue];
//////// If i do like this, i have warning - "Initializing 'NSNumber *__strong' with an expression of incompatible type 'double'
[self.programStack addObject:operand];
}
I don't understand what this warnings are all about.
So the question is can I somehow put in Array NSNumber and NSString using id method, or how should I do it?
Can i 'transform' argument from 'id' method into NSNumber?
Yes you can "transform" your argument of operand, but you'd need to do a cast.
Also, the line:
NSNumber *digitToStack = [NSNumber numberWithDouble:operand];
fails because "operand" is an Objective C object while that function is expecting a C-style double type (which is NOT an Objective C object).
Here's some code I wrote off the top of my head:
// Let's make operand always be a NSString object
// since that's what is being passed in from the label
- (void) pushOperand:(NSString *)operand
{
double doubleValueFromOperand = [operand doubleValue];
if(fabs(doubleValueFromOperand) != HUGE_VAL)
{
NSNumber *digitToStack = [NSNumber numberWithDouble:doubleValueFromOperand];
if(doubleValueFromOperand != 0.0)
{
[self.programStack addObject:digitToStack];
return;
} else {
// because NSString's doubleValue also returns 0.0 for a
// non-numerical string, let's make sure the input from the label
// is not 0.0
if([operand compare: #"0.0" options: NSCaseInsensitiveSearch range: NSMakeRange(0, 3)] == NSOrderedSame)
{
// the operand string *is* a 0.0 input, so let's add it to your stack and return
[self.programStack addObject: digitToStack];
return;
}
}
}
// if we get to this point, we probably have a non-numerical string object
[self.programStack addObject: operand];
}
This code hasn't been tested, has no warranties, and could certainly use a further cleaning up and optimization (e.g. the check for "0.0" isn't what I would put into production code, myself).
But hopefully this is enough to get you further along, Sasha!

NSInteger != nil

How can I check that the NSInteger is valid?
NSInteger previousScore = [[self score] integerValue];
if (previousScore != nil) {
//do something
}
If you want to check for validity in your code, you'd do something like:
NSNumber *previousScore = [self score];
if ( previousScore != nil ) {
NSInteger previousScoreValue = [previousScore integerValue];
// do something
}
This works as you are getting back an object, not a primitive value.
NSInteger isn't an object. It's simply a typecasted primitive int. Therefore, it will never be nil. Just treat it the same as if you were using an int straight up.
Edit:
To expound upon Cesar's comment, on 64-bit systems NSInteger is actually a long and on 32-bit systems it's an int.

how to convert the value of nsarray to integer value

I working on grouped table view based work in that in that i want to convert the value of NSarray into integer for specifing to section value of numberOfRowsInSection but it throws expection on putting following code.
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
int sec;
if (section == 0){ sec=6; }
else if(section == 1){ sec=6; }
else if(section == 2){
sec=[[rsvn_detail objectAtIndex:0] objectForKey:#"totalrecord"];
}
return sec;
}
Anybody help to recify it advance thanks for your suggestion
Regards,
sathish
NSArray and NSDictionary can only hold Objective-C objects. An int is not an object. It is likely the number is wrapped as an NSNumber. To convert an NSNumber back to an int, call -intValue:
sec = [[[rsvn_detail objectAtIndex:0] objectForKey:#"totalrecord"] intValue];
// ^^^^^^^^
Of course, make sure rsvn_detail is really an NSArray of NSDictionary. Without -intValue won't cause exceptions, only compiler warning/error will be raised.
What is the exception? Seems that [[rsvn_detail objectAtIndex:0] objectForKey:#"totalrecord"]; is causing the problem.

How to convert and compare NSNumber to BOOL?

First I convert BOOL value to NSNumber in order to put it into NSUserDefaults. Later I would like to retrieve the BOOL value from the NSUserDefaults, but obviously I get NSNumber instead of BOOL. My questions are?
how to convert back from NSNumber to BOOL?
How to compare NSNumber to BOOL value.
Currently I have:
if (someNSNumberValue == [NSNumber numberWithBool:NO]) {
do something
}
any better way to to the comparison?
Thanks!
You currently compare two pointers. Use NSNumbers methods instead to actually compare the two:
if([someNSNumberValue isEqualToNumber:[NSNumber numberWithBool:NO]]) {
// ...
}
To get the bool value from a NSNumber use -(BOOL)boolValue:
BOOL b = [num boolValue];
With that the comparison would be easier to read for me this way:
if([num boolValue] == NO) {
// ...
}
Swift 4:
let newBoolValue = nsNumberValue.boolValue
NSUserDefaults has two methods to transparently operate with booleans:
- (BOOL)boolForKey:(NSString *)defaultName
- (void)setBool:(BOOL)value forKey:(NSString *)defaultName
The ONLY way I managed to finagle a NSNumber's "booleanity" from its NSConcreteValue(doh!) was with the following...
id x = [self valueForKey:#"aBoolMaybe"];
if ([x respondsToSelector:#selector(boolValue)] &&
[x isKindOfClass:objc_getClass("__NSCFNumber")])
[self doSomethingThatExpectsABool:[x boolValue]];
Every other trick... FAILED. Buyer beware, this isn't foolproof (__NSCFNumber may well be platform/machine specific - it is solely Apple's implementation detail)... but as they say.. nothing else worked!