How to get the value for key #int from NSDictionary? - ios

I am Creating a NSDictionary and adding a key value pair as below
NSDictionary* dictionary = #{ #0: #"I am the value" };
and retrieving the value as below
NSString* value = [dictionary valueForKey:#0];
Application crashed for doing this, I don't understand the reason, I am giving the same data type and value.
What is the datatype of #0, I guess it is NSNumber, If not correct me.

Yes, it's NSNumber type however the problem is somewhere else.
You should call objectForKey instead of valueForKey which is mainly used for KVO.
NSString *value = [dictionary objectForKey:#0];
or better:
NSString *value = dictionary[#0];

valueForKey: is not the proper method for what you are trying to achieve.
you should use:
NSString* value = [dictionary objectForKey:#0];
ValueForKey is for key value coding and expect a NSString as parameters

Related

Convert NSNumber to long

I am trying to convert a NSNumber to long but I get this error:
[__NSSingleObjectArrayI intValue]: unrecognized selector sent to
instance
Here is my code:
NSNumber *dbversion = [settings valueForKey:#"Version"];
long dbver = [dbversion longValue];
What am I doing wrong here?
*settings is a NSArray and "Version" is the key for a long value.
You are caught in the Key-Value Coding trap.
In some cases the result of valueForKey is an array which the error message clearly states.
Don't Never use valueForKey(unless you know what KVC does and you need KVC), use key subscription.
And as settings is an array you might get the first item
NSNumber *dbversion = settings[0][#"Version"];
and int is not long
long dbver = [dbversion longValue];
However on a 64-bit machine I recommend to use NSInteger
NSInteger dbver = dbversion.integerValue;
//I think you are storing string from dictionary "settings" to NSNumber so it's showing error like you mention in question.
Please Try with solution. May this help you.
NSNumber *dbversion = [NSNumber numberWithLong:[[settings valueForKey:#"Version"] longLongValue]];
int dbver = [dbversion longValue];

What is the difference between #"1.5" and #(1.5) while setting the value in NSDictionary?

In iPhone project,
It was while I was while setting Value in dictionary,
NSMutableDictionary*dictionary=[[NSMutableDictionary alloc] init];
[dictionary setValue:#(2.8) forKey:#"Why"];
AND,
NSMutableDictionary*dictionary=[[NSMutableDictionary alloc] init];
[dictionary setValue:#"2.8" forKey:#"Why"];
My question is Why not #"2.5" and #(2.5) ?
You have two questions, it would be better to have a single question.
But as to the difference,#"2.5" is an NSString where #(2.5) is an NSNumber. There is a big difference between textual and numeric data.
As for why you need an NSNumber and not NSString is obvious: the kerning is a numeric value.
using the #() syntax you can box arbitrary C expressions. This makes it trivial to turn basic arithmetic calculations into NSNumber objects see below:
double x = 24.0;
NSNumber *result = #(x * .15);
NSLog(#"%.2f", [result doubleValue]);
You can also refer NSNumber object as #"" string but cant make calculations like above example. In your case both are acceptable but here calculation makes difference.
When you use
#"2.5" it's behave like a string
NSMutableDictionary*dictionary=[[NSMutableDictionary alloc] init];
[dictionary setValue:#"2.8" forKey:#"Why"];;
NSString *a = [dictionary ValueforKey:#"Why"];
but when you use #(2.8) then it's behave like a NSNumber
NSMutableDictionary*dictionary=[[NSMutableDictionary alloc] init];
[dictionary setValue:#(2.8) forKey:#"Why"];;
NSNumber *a = [dictionary ValueforKey:#"Why"];
#(2.8) is a type of NSNumber.
#"2.8" is a type of NSString.
Both the type and value were different between there two.

Use existing string as valueForKey value

I am trying to use a string ("levelNumberString") as a valueForKey in an NSDictionary. When I use a string like #"1", it all works perfectly, but when I decide to swap out that kind of string for levelNumberString, it gives me a SIGABRT error. The integer levelInt is an integer that decides what level the app is at. When the view is loaded, it is worth 1, and its value is taken up by the "levelNumberString" string.
This is my code (it's in viewDidLoad, if that helps at all):
NSString *levelNumberString = [NSString stringWithFormat:#"i%", levelInt];
NSDictionary *packDict = [NSDictionary dictionaryWithDictionary:[rootDict valueForKey:levelNumberString]];
The above code is what is giving me the error.
Thanks in advance!
The problem is over here #"i%" it should be #"%i"
NSString *levelNumberString = [NSString stringWithFormat:#"%i", levelInt];
NSDictionary *packDict = [NSDictionary dictionaryWithDictionary:[rootDict valueForKey:levelNumberString]];

How to append a float value as float in dictionary?

I need to calculate a MD5 values with a json value to the server like,
{
"name":"swift",
"version":1.0,
"edition":1,
"date":"2014-12-26"
}
In this json the version needs to be send as float 1.0 not 1 and edition as integer 1.
So, I have tried to create a dictionary and done a NSJSONSerialization as,
NSDictionary *d = #{#"name":#"swift",
#"version":[NSDecimalNumber decimalNumberWithString:#"1.0"],
#"edition":[NSNumber numberWithInt:1],#"date":#"2014-12-26"};
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:d options:0 error:nil];
But this is creating a json response as
{
"name":"swift",
"version":1,
"edition":1,
"date":"2014-12-26"
}
So the MD5 value is mismatching.
Can anyone help me with this to create a json with float value for "version" with decimal point (1.0) ?
There is nothing wrong with sending the numeric value 1.0 as simply 1 in JSON. Though you might have a little luck getting the .0 if you encoded a floating point in an NSNumber, vs using an NSDecimalNumber.
`... #"version":#(1.0)...`
The full dictionary:
NSDictionary *d = #{#"name":#"swift",
#"version":#(1.0),
#"edition":#(1),
#"date":#"2014-12-26"};
Create the NSMutableDictionary, convert the number to an NSNumber and put it into the NSMutableDictionary.
NSMutableDictionary *dict = [NSMutableDictionary dictionary];
float value = 1.0;
NSNumber *number = [NSNumber numberForFloat:value];
[dict setObject:number forKey:#"version"];
or using literals replace the above two lines with:
dict[#"version"] = #(value);

IF statement issue in IOS using NSString

My if statement won't work. active returns 1 but will not work in the IF statement
JSONDecoder *jsonKitDecoder = [JSONDecoder decoder];
NSDictionary *dict = [jsonKitDecoder objectWithData:jsonData];
NSString *userid = [dict valueForKeyPath:#"users.user_id"];
NSString *active = [dict valueForKeyPath:#"users.active"];
NSLog(#"%#",userid); // 2013-06-20 03:03:21.864 test[81783:c07] (74)
NSLog(#"%#",active); // 2013-06-20 03:03:21.864 test[81783:c07] (1)
if ([active isEqualToString:#"1"]){
// Do something
}
I can't seem to get this IF to work. Do I need to change the NSString to a int?
For starters, use a modern style for retrieving values from dictionaries, rather than valueForKeyPath:.
NSDictionary* users = dict[#"users"];
id active = users[#"active"];
Once you're using a modern style, my guess is that the active value is actually an NSNumber representing a boolean value. So your if block would read:
if([active isKindOfClass:NSNumber] && [active boolValue]) {
//active is an NSNumber, and the user is active
}
The syntax of your if statement is just fine. I would try the alternate method for retrieving values from a dictionary as mentioned above.
NSString *active = #"1";
if ([active isEqualToString:#"1"])
{
// Do something
NSLog(#"It works!");
}
More than likely the "users.active" object being returned from that NSDictionary-ized JSON stream is a "BOOL" or a "NSInteger" as the payload of a NSNumber object and it's not a NSString object.
Try using:
NSNumber * activeNumber = [dict valueForKeyPath: #"users.active"];
and see if "if ([activeNumber boolValue] == YES)" works better for you.

Resources