Display NSNumber In Label - iphone

I am trying to display an NSNumber from an array with keys into an UILabel. Here is my current code: marblesNeeded.text = [[[records objectAtIndex:0] valueForKey: #"marblesneeded"] intValue];
I also get the error:
warning: Semantic Issue: Incompatible integer to pointer conversion assigning to 'NSString *' from 'int'
Thanks

You need to create an NSString to set the text of a UILabel.
marblesNeeded.text = [NSString stringWithFormat:#"%i",[[[records objectAtIndex:0] valueForKey: #"marblesneeded"] intValue]];
In the format %i denotes that you will be providing an integer value after the format.
Edit:
As some comments have noted NSNumber does have a stringValue, it does work but is not my personal preference because it gives you little control as to the format of the string. Consider this example.
NSNumber *number = [NSNumber numberWithFloat:3.25];
NSLog(#"%#",number.stringValue); // Will print 3.25
NSLog(#"%#",[NSString stringWithFormat:#"%i",number.intValue]); // Will print 3
Since the question envolved printing an intValue this more explicit format may be necessary.

marblesNeeded.text = [[[records objectAtIndex:0] valueForKey: #"marblesneeded"] stringValue];

Related

Xcode Gives Strange Output From NSArray

When I run this code, the output is some 1084848 to the console. I can't figure out why such odd output... here is the code.
#import <Foundation/Foundation.h>
int main (int argc, const char * argv[])
{
NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
NSMutableArray *array = [[NSMutableArray alloc] init];
int someNumber = 3;
[array addObject:[NSNumber numberWithInt:someNumber]];
NSLog(#"%i" , [array objectAtIndex:0]);
[pool drain];
return 0;
}
the "%i" format specifier expects an integer, not an Object.
Try NSLog(#"%i" , [[array objectAtIndex:0] intValue]);
XCode is probably giving you a warning on this line: something like "Conversion specifies type 'int', but argument has type 'id'".
Here's the pseudocode of your program:
//
// Inside of your main function....
//
// Set up the Autorelease pool and then create an array
//
// Declare an int
//
// Add the int to an array, while wrapping it in an NSNumber
//
// Log the value of the first object in the array, using the int formatter
//
// Clean up and return
//
You are logging the first object in the array, but NSArray cannot hold a primitive that's not wrapped in an Objective-C object.
To better understand your code, try changing these lines of code:
int someNumber = 3;
[array addObject:[NSNumber numberWithInt:someNumber]];
Expand them a little. Try this:
int someNumber = 3;
NSNumber *aNumber = [NSNumber numberWithInt:someNumber];
[array addObject:aNumber];
So, you've correctly wrapped the int in an NSNumber, but you're not unwrapping it. You need to ask your NSNumber for the int that it holds like so:
[[array objectAtIndex:0] intValue];
Or, to do the logging in one line:
NSLog(#"%i" , [[array objectAtIndex:0] intValue]);
The characters "%i" is called a "formatter". Different kinds of values require different formatters. When you are using an Objective-C object, you use "%#". For an NSInteger or int, you'd use %i. For a float, you'd use "%f". The point is that you need to either unwrap that number, or use the Objective-C formatter for strings.
A quick note about that weird value you were getting earlier: That's a memory address in RAM. It's the closest thing you're going to get when you use an incorrect formatter. In some cases, using the wrong formatter will cause an EXC_BAD_ACCESS. You were "lucky" and got a weird value instead of a dead program. I suggest learning about strings and formatters before you move on. It will make your life a lot easier.
When you use %i for integer values then you should give arguments as integer as below
NSLog(#"%i" , [[array objectAtIndex:0] intValue]);
But when you want object to be displayed then you must use %# which identifies object in general case as below:
NSLog(#"%#", array);

Problem with int in Objective C

singelton.categoryId = (int)[categories.categoriesId objectAtIndex:indexPath.row];
NSLog(#"%d", singelton.categoryId);
singelton.categoryId is from type int.
But when I try to print it number is random, but if I do this NSLog(#"%#", singelton.categoryId); the printed value is right.
I need to print it with %d.
Can someone help me?
Use intValue method to get the integer representation of a NSString/NSNumber. Try,
singelton.categoryId = [[categories.categoriesId objectAtIndex:indexPath.row] intValue];
I am assuming the array returns you an NSNumber. So try this out.
int catId = [ ((NSNumber*) [categories.categoriesId objectAtIndex:indexPath.row] ) intValue];
NSLog(#"%d, catId )
try the following:
NSLog(#"%d", [singelton.categoryId intValue]);
The category ID as returned by objectAtIndex: is an object, most probably an NSNumber. By casting it to int you get the address of the object, not the numeric value stored in it. The correct code would be something like this:
singleton.categoryID = [[… objectAtIndex:…] intValue];
Try do do this in this way:
singelton.categoryId = [[categories.categoriesId objectAtIndex:indexPath.row] intValue]
It's because you can't store ints in array - they must be NSNumbers.
There's no way that's coming from an int primitive type when it's a proper object (assuming that objectAtIndex behaves here as elsewhere in Objective-C--i.e., it's not your own method. So, you'll need to ask for the intValue:
[[categories.categoriesId objectAtIndex:indexPath.row] intValue]
if it is an available method. What class is categoriesID?

Convert NSString to Integer in objective - c

I have an array that stores each digit of a phone number as a string. I then pass the phone number digit string as an argument for objectAtIndex: method of NSArray like this: [myArray objectAtIndex: [myString intValue]]; The compiler says I need to cast the String but I am already doing that. What is wrong?
Update:
Here's my actual line of code:
NSMutableArray *tmp = [[NSMutableArray alloc] initWithArray:[charHolder objectAtIndex:[[phoneNumDigits objectAtIndex:i]intValue]]];
This is where the error is, phoneNumDigits is an array of each digit of the phone number, charHolder is the array holding the array of letters associated with each digit.
Your question is a little confusing to me. Here is how I understand what you want to do:
You have an NSArray named phoneNumDigits. This array contains a few NSString objects. Each string is something like #"1" or #"4" and represents a single digit of a phone number.
Now you want to convert each of those digit strings to int or NSInteger and want to store these integers in another array.
If I understood you correctly, here is my answer:
You cannot exactly do what you want, because you can't put a simple data type like an int or a float into an NSArray.
That's why there is the wrapper class NSNumber. You can package a simple int in an NSNumber and store this NSNumber in an NSArray.
So to get your string digits from the phoneNumDigits into the tmp array you could use this code:
for (NSString *digitAsString in phoneNumDigits)
{
NSNumber *digitAsNumber = [NSNumber numberWithInt:[digitAsString intValue]];
[tmp addObject:digitAsNumber];
}
To get the ints out of the tmp-NSArray you would use
int digit = [[tmp objectAtIndex:idx] intValue];
I hope this helps, but I'm not sure I understand what you want to do here. I could be completely missing the point. Maybe you could share some more code.
NSMutableArray *tmp = [[NSMutableArray alloc] initWithArray:[charHolder objectAtIndex:[[phoneNumDigits objectAtIndex:i]intValue]]];
objectAtIndex returns a generic object (id). It has no idea that the object in the array is a string as it could be anything. So you need to cast it. Or to increase readabilty, create variables for them. Eg:
int phoneNumberDigit = [phoneNumDigits objectAtIndex:i];
NSArray *chars = [charHolder objectAtIndex:phoneNumberDigit];
NSMutableArray *tmp = [[NSMutableArray alloc] initWithArray:chars];

How can I read Float from Core Data / iPhone?

I have Float values stored in Core-Data.
What is the code to use to read these values in an NSstring ?
Core-Data uses NSNumber objects to store the float value.
To get the 'raw' float value and put it into a string you would use something like this.
NSNumber *floatNumber = [managedObject valueForKey:#"myFloatValueKey"];
float myFloat = [floatNumber floatValue];
NSString *floatString = [NSString stringWithFormat:#"%f", myFloat];
Maybe a NSNumberFormatter would be useful.
Well, assuming that you mean your Core Data entity has an attribute of type float, you could simply access that field after you perform a fetch of that object.
[[self managedObjectContext] fetchObjectsForEntityName:#"EntityName" withPredicate:
#"(attribute LIKE[c] 'value') AND (attribute2 > %#)", someValue];
You could then put this in string format with this:
NSString* myNewString = [NSString stringWithFormat:#"%f", [[managedObject floatAttribute] floatVal]];

Problem when converting NSString to NSNumber in iPhone

I am having problem when converting string (YaxisData) to NSNumber. I have to return a NSNumber for Core-plot to get the graph done but its not working. Here's the sample code
-(NSNumber *)numberForPlot:(CPPlot *)plot field:(NSUInteger)fieldEnum recordIndex:(NSUInteger)index{
NSNumber *num = [NSNumber numberWithDouble:[[YaxisData objectAtIndex:index] doubleValue]];
return num;
}
num returns junk data such as -1 or 993494949494 but when I log the double value of number, it prints the correct value. I am not able to return this double value as the function signature requires only the NSNumber to be returned.
NSLog(#"Number: %f", [num doubleValue]);
I am stuck here and would really appreciate any help in this regard. Thanks!
Would this give a better result somehow?
NSString *aString = [YaxisData objectAtIndex:index];
NSLog(#"%#", aString);
double value = [aString doubleValue];
NSLog(#"%f", value);
NSNumber *number = [NSNumber numberWithDouble:value];
NSLog(#"%#", number);
If not, could you show the results of the NSLog()'s?
I know that in practice it seems the same code, yet one might not be so sure that -objectAtIndex: always returns a string. It might be a localization issue as well (commas and dots for decimal separator might get mixed up, this would definitely mess up your results. In case of a localization issue, check the following link:
How to convert an NSString into an NSNumber