How can an int be converted into an id? - ios

I have an array, and the contents of it are objects of type id, but I need to turn them into type int. Is there any way I can make the array read the data as ints, or turn the id into an int?
NSArray *array = [string componentsSeparatedByString:#"\n"];
int foo = array[0]; /*Warning: Incompatible pointer to integer conversion initializing 'int' with an expression of type 'id' */

componentsSeparatedByString: docs says:
Return value
An NSArray object containing substrings from the receiver that have been divided by separator.
So your fileContents contains an array of NSStrings. fileContents[0] is then the first NSString instance in the array. And you can convert NSString to int or preferably NSInteger by calling
[string intValue];
[string integerValue];
So your code should look like this (assuming array contains at least 1 object, don't forget to check this):
int object1 = [fileContents[0] intValue];
Or even better include typecasting for better code readability
int object1 = [(NSString *)fileContents[0] intValue];

You should use intValue to convert to int.
int object1 = [fileContents[0] intValue];

Related

How to convert iOS id type which holds int to NSString?

I have an id which holds an int. I need to cast it to an NSString and append it to another NSString.
I've trued different approaches but I have different type of errors. My confusion is that int is not an object type.
My code is:
NSString *str = [dict objectForKey:[NSNumber numberWithLongLong:ID]];
In this case I have (int) 1000.
When I try to append it to NSString I get an exception.
How can I properly cast from an id, which holds int, to NSString ?
NSString *str = [[dict objectForKey:[NSNumber numberWithLongLong:ID]] stringValue];

How to get last array object as int

How can I get the last object from an array as an int, for example if I have 20 objects in the array, how can I get the last object as an int variable that = 20. Or if the array had 999 objects, the last object int would = 999.
How can I do this? I have tried using (int)array.lastobject but have had no luck, any help would be greatly appreciated.
It depends on what type of objects are being stored in the array? if they are NSNumber or NSString than you can do this:
int myVar = [[array lastObject] intValue];
Edit:
Your question is rather confusing it also seems that you want array count instead of last object? If thats the case than use this:
int myVar = [array count];
Option 1
int yourVariable = [[yourArray lastObject] intValue];
Option 2
int yourVariable = [[yourArray objectAtIndex:([yourArray count]-1)] intValue];
you can use lastObject method to get last object from array
int lastValue = [[yourArray lastObject] intValue];

Check whether the NSArray object at index is of kind NSString Or NSNumber

This is my NSArray :
(
"tag_name",
3,
"mp4_url",
4,
0,
"back_tag",
5,
1,
"part_id",
"related_list",
2
)
I need to put all the numerical values in some another array.
I used the following code to check whether the value fetched from the array was a numeric or a string, but it didn't work. Every time i get the value from an array as NSString.
for (int i=0; i<arr.count; i++) {
id obj=[arr objectAtIndex:i];
if ([obj isKindOfClass:[NSString class]])
{
// It's an NSString, do something with it...
NSLog(#"its string");
}else{
// It's an Numerical value, do something with it...
NSLog(#"its integer value");
}
}
I know that array stores only kind of objects in it, so while fetching i'm getting the value as NSString(i.e object). But is there anyway to check whether the value stored was a numeric value.
Please can anyone help me..
Thanks
You can't just turn an NSString into an NSNumber but there are ways that you can try to get he numeric value out of them.
This is one option but you could also have a look at NSNumberFormatter.
If all of the numbers are integers then you could do something like this...
// always use fast enumeration
for (NSString *string in arr) {
NSInteger integer = [string integerValue];
// have to check explicitly for 0 as a non-numeric would return 0 above
if ([string isEqualToString:#"0"]
|| integer != 0) {
// it is an integer numeric string
} else {
// it is a string
}
}

Conversion issue from NSNumber to NSString

I'm parsing data from a JSON webservice and adding it to the database so when I insert an int, I have to convert it to NSNumber in this way it's working fine: 24521478
NSString *telephone = [NSString stringWithFormat:#"%#",[user objectForKey:#"telephone"]];
int telephoneInt = [telephone intValue];
NSNumber *telephoneNumber = [NSNumber numberWithInt:telephoneInt];
patient.telephone = telephoneNumber;
but when I want to display it and convert the NSNumber to NSString I'm getting wrong numbers: -30197
NSString *telephoneString = [NSString stringWithFormat:#"%d", [user.telephone intValue], nil];
labelTelephone.text =telephoneString ;
Can someone explain this?
NSNumber comes with dedicated methods for each data type.If you want to convert NSNumber to NSString use:
NSString *telephoneString = [user.telephone stringValue];
The issue may coming because of the data type you used for the variable patient.telephone
If you have control over the web service, then you should return the telephone number as string in the JSON
Reasons
if the telephone number begin with zero then the NSNumber will remove that zero as it has no value (ex: 00123456789 will be 123456789 which will wrong data)
You will not be able to display the telephone number is a user friendly way by adding "+" and "-" (ex: +123-456-789)
You really should make the json return the number as string if you have a control over that

Add NSUInteger to NSMutableArray

Hello I am working on a project and I am trying to add an NSUInteger to an NSMutableArray. I am new to Objective-C and C in general. When I run the app NSLog displays null.
I'd appreciate any help anyone is able to provide.
Here is my code
-(NSMutableArray *)flipCardAtIndex:(NSUInteger)index
{
Card *card = [self cardAtIndex:index];
[self.flipCardIndexes addObject:index];
if(!card.isUnplayable)
{
if(!card.isFaceUp)
{
for(Card *otherCard in self.cards)
{
if(otherCard.isFaceUp && !otherCard.isUnplayable)
{
int matchScore = [card match:#[otherCard]];
if(matchScore)
{
otherCard.unplayable = YES;
card.unplayable = YES;
self.score += matchScore * MATCH_BONUS;
}
else
{
otherCard.faceUp = NO;
self.score -=MISMATCH_PENALTY;
}
break;
}
}
self.score -=FLIP_COST;
}
card.faceUp = !card.isFaceUp;
}
NSLog(#"%#",self.flipCardIndexes[self.flipCardIndexes.count-1]);
return self.flipCardIndexes;
}
NSArray (along with its subclass NSMutableArray) only supports objects, you cannot add native values to it.
Check out the signature of -addObject:
- (void)addObject:(id)anObject
As you can see it expects id as argument, which roughly means any object.
So you have to wrap your integer in a NSNumber instance as follows
[self.flipCardIndexes addObject:#(index)];
where #(index) is syntactic sugar for [NSNumber numberWithInt:index].
Then, in order to convert it back to NSUInteger when extracting it from the array, you have to "unwrap" it as follows
NSUInteger index = [self.flipCardIndexes[0] integerValue]; // 0 as example
You can only add objects to NSMutableArrays. The addObject accepts objects of type id, which means it will accept an object.
NSIntegers and NSUIntegers, however, are not objects. They are just defined to be C style variables.
#if __LP64__ || NS_BUILD_32_LIKE_64
typedef long NSInteger;
typedef unsigned long NSUInteger;
#else
typedef int NSInteger;
typedef unsigned int NSUInteger;
#endif
As you can see, they are just defined to be ints and longs based on a typedef macro.
To add this to your array, you need to first convert it to an object. NSNumber is the Objective C class that allows you to store a number of any type. To make the NSNumber, you will want to you the numberWithInt method, passing your variable as the parameter.
NSNumber *number = [NSNumber numberWithInt:card];
Now that your variable is wrapped in an object, you can add it to the array.
[self.flipCardIndexes addObject:number];
Finally, if you want to retrieve the element at a future time, you have to remove the object and then convert it back to an int value you can use. Call
NSNumber *number = [self.flipCardIndexes objectAtIndex:index];
Where index is the index of the card you are trying to retrieve. Next, you have to convert this value to an integer by calling integerValue.
NSUInteger *value = [number integerValue];

Resources