NSInteger != nil - iphone

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.

Related

Int decimal count in iPhone

I need to know whatever an int64_t has decimals, and how many. This should be placed in if-else-statement. I tried this code, but it causes the app to crash.
NSNumber *numValue = [NSNumber numberWithInt:testAnswer];
NSString *string = [numValue stringValue];
NSArray *stringComps = [string componentsSeparatedByString:#"."];
int64_t numberOfDecimalPlaces = [[stringComps objectAtIndex:1] length];
if (numberOfDecimalPlaces == 0) {
[self doSomething];
} else {
[self doSomethingElse];
}
Your question doesn't make a lot of sense; you are creating the NSNumber object from an int so it will never have decimal places, as an int cannot store them. The reason your code is crashing is that it assumes that the array of components is always at least 2 elements long (as you use objectAtIndex:1).
This is better, though still not that good:
NSString *answer = ...; // From somewhere
NSArray *stringComps = [answer componentsSeparatedByString:#"."];
if ([stringComps count] == 0) {
[self doSomething];
} else if [stringComps count] == 1) {
[self doSomethingElse];
} else {
// Error! More than one period entered
}
This still isn't a very good test as it only tests if a period (.) has been entered, not a valid number.

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.

Sort NSMutableDictionary keys by object?

Okeh. Here is the deal:
Have have a NSMutualDictionary with words as keys (say names). The value objects is a NSNumber (like rating)
NSMutableDictionary *dictionary = [[NSMutableDictionary alloc] init];
[dictionary setObject:[NSNumber intValue:1] forKey:#"Melvin"];
[dictionary setObject:[NSNumber intValue:2] forKey:#"John"];
[dictionary setObject:[NSNumber intValue:3] forKey:#"Esben"];
I want to sort them with the highest ratings first.
I know I'm going to do it like this:
[searchWords keysSortedByValueUsingSelector:#selector(intCompare:)];
But not sure how to implement intCompare. (the compare method)
Can anybody point me in the right direction?
- (NSComparisonResult) intCompare:(NSString *) other
{
//What to do here?
}
I want to get an NSArray with {Esben, John, Melvin}.
Since the objects you put into the dictionary are NSNumber instances you should change the method signature a bit. But the full implementation is really easy:
-(NSComparisonResult)intCompare:(NSNumber*)otherNumber {
return [self compare:otherNumber];
}
In fact I see no reason as to why you need to do your own intCompare: method, when you could go with the compare: that NSNumber already has.
These constants are used to indicate how items in a request are ordered.
enum {
NSOrderedAscending = -1,
NSOrderedSame,
NSOrderedDescending
};
typedef NSInteger NSComparisonResult;
That is taken from Apple's dev documentataion on Data types... now all you have to do is check which one is bigger. All of this is done for you though. Simply pass in #selector(compare:) and that should do it. As your values are NSNumbers and NSNumber implements the compare: function. Which is what you want :)
NSArray *sortedArray = [searchWords sortedArrayUsingSelector:#selector(compare:) ];
or you might well as used, here is the implementation of your intCompare selector
- (NSComparisonResult) intCompare:(NSString *) other
{
int myValue = [self intValue];
int otherValue = [other intValue];
if (myValue == otherValue) return NSOrderedSame;
return (myValue < otherValue ? NSOrderedAscending : NSOrderedDescending);
}

Objective c Setting picker value from NSDictionary

Another, probably simple problem that, having tried for a good few hours now I'm pretty stumped on. Simply, I want to set the value of a picker from a NSDictionary, I don't mind! Every way I have tried pretty much gives me the warning Passing argument 1 of selectRow inComponent animated' makes integer from pointer witout a cast. Which makes sense, though I seem to be failing miserable at fixing it! Any help would be greatly appreciated! Snippet of code below...
NSArray *myValue = [parsedJson objectForKey:#"Details"];
NSEnumerator *myEnumerator = [myValue objectEnumerator];
NSDictionary* myItem;
int i = 0;
while (myItem = (NSDictionary*)[myEnumerator nextObject])
{
[myPickerView selectRow:[myItem objectForKey:#"Value"] inComponent:i animated:YES];
i++;
}
Assuming your value responds to intValue message (e.g. number is stored in NSNumber or NSString) then the following should work:
[myPickerView selectRow:[[myItem objectForKey:#"Value"] intValue]
inComponent:i animated:YES];
The selectRow parameter is expecting an integer, try this:
[myPickerView selectRow:[[myItem objectForKey:#"Value"] integerValue] inComponent:i animated:YES];

How to compare a NSNumber in an if

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)
{
...
}