Adding negative NSNumber value to a NSDictionary - objective-c

As someone who has some programming experience it pains me to be asking this question. I just started playing around with objective-c a few days ago and I am trying to simply add NSNumber objects to an NSDictionary. The problem is, when I add an NSNumber object with a negative value it seems as if it is being added as a string not an NSNumber.
Here is how I am initializing the dictionary:
testDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithDouble:-3],#"x",
[NSNumber numberWithDouble:7, #"a",
nil];
I guess I really have two questions, 1.) Is this not how you create an NSNumber object that has a negative value?
2.) When I print out the dictionary I get the following:
NSLog(#"dictionary = %#", self.testDict);
a = 7;
x = "-3";
Why the double quotes around the -3?

You're correct, and everything's fine. That's just the dictionary -description being misleading.
To verify, break on the NSLog() and try (warning: typed on iPhone):
p [testDict objectForKey:#"x"];
It should reveal it to be an NSNumber instance.

#Conrad Shultz is right, it's just an artifact of how the the description method for the NSDictionary prints the dictionary contents (which is what is happening when you pass the dictionary to NSLog)
Another way to verify that everything is really working as expected is to iterate through the dictionary members and print the descriptions of the indivdual objects. Then you can see your negative number description looks like a number rather than a string.
NSDictionary* testDict = [[NSDictionary alloc] initWithObjectsAndKeys:[NSNumber numberWithDouble:-3],#"x", [NSNumber numberWithDouble:7], #"a", nil];
NSArray *keys = [testDict allKeys];
for (NSString *key in keys) {
NSLog(#"%# => %#", key, [testDict objectForKey:key]);
}
Console output is:
2012-02-29 12:38:39.544 test10[1055:f803] x => -3
2012-02-29 12:38:39.546 test10[1055:f803] a => 7

Related

NSNumber returns wrong value

I have NSDictionary and I assign value of 'price' key to NSNumber property of my object but when I log number value, it is an strange negative number!
item.price = [food valueForKey:#"price"];
price property is NSNumber
[[food valueForKey:#"price"] class]
will print __NSCFNumber which is right.
[[food valueForKey:#"price"] intValue]
returns 0x000000000000c350 which is 50000 thats right
but when I log item.price or [item.price integerValue] it is -15536 which is completely wrong!
Any idea?
food json sample:
{
"title":"Pizza",
"price":50000
}
Guess what?
all of this logs and problems shows my NSNumber property can't store some integers. but what range of integers? integers which are between -32,768 / 32,768
but why? because I have define my managed object price property of kind NSInteger 16!
I should define it as NSInteger 32
Let's say you are trying to do this:
NSDictionary *inventory = #{
#"price" : [NSNumber numberWithInt:50000]
};
NSNumber *num= [inventory valueForKey:#"price"];
NSLog(#"%d,%f,%ld,%#",num,num,num,num);
and the log will display as:
800002,-0.000000,-5764607523033434878,50000
all of them are totally different.The last one is the correct NSNumber object
NSNumber is an object ,so you need to use %# to log it and remaining %d,%f,%ld are not objects.

Get list of Values for an NSArray of NSDictionary

I've got the following NSArray :
NSArray myArray = #[#{#300:#"5 min"},
#{#900:#"15 min"},
#{#1800:#"30 min"},
#{#3600:#"1 hour"}];
I want the list of value of my dictionaries :
#[#"5 min",#"15 min",#"30 min",#"1 hour"]
And the list of key of my dictionaries :
#[#300, #900, #1800, #3600]
What is the best way to do that ? I was thinking about predicate, but I don't know how to use it ?
Without some code to show how you'd want to go about this it is difficult to be sure exactly what you are after, and there is a bit of confusion in the question.
First, a predicate is exactly that - a statement that can be proven true or false. Predicates are hence used in logic expressions, including those employed implicitly in database queries - such as Core Data.
That is not what you want, if I read your question correctly. What you want is to reduce the complexity of your data model, removing some excess (one would hope) information in the process. A sort of flattening of an array of dictionaries.
Fair enough.
I can also see how the confusion with predicates came about - they are most often constructed using Key-Value Coding. KVC, as it is also known, is a very powerful technique that can accomplish what you are after. It just does not have much to do with a logic statement.
Having cleared that up, with KVC you can do what you want, and with minimal fuss. It goes like this:
NSArray *values = [myArray valueForKeyPath: #"#unionOfArrays.#allValues"];
NSArray *keys = [myArray valueForKeyPath: #"#unionOfArrays.#allKeys"];
A brief explanation might be in order:
The results that we want are
All the values (or keys) of each dictionary, obtaining an array of arrays of values (or keys)
Then we want to flatten these arrays into a single array.
To obtain all values (or keys) from a dictionary using KVC, the special key is #allValues or #allKeys, respectively.
The #unionOfArrays operator makes a union of the arrays obtained from the expression that follows it, i.e., flattens it into the array you wanted.
The price you pay for this coding simplicity is that you have to use KVC key paths with collection operators, which are just strings in your code. You therefore lose any help from the compiler with syntax and it doesn't check that the keys you enter exist in the objects. Similarly, the debugger and error messages are unhelpful if you mistype or use the wrong operator, for instance.
You can use dictionary property allValues to get all values of dictionary.
Try this code in your case
NSArray *myArray = #[#{#300:#"5 min"},
#{#900:#"15 min"},
#{#1800:#"30 min"},
#{#3600:#"1 hour"}];
NSMutableArray *arr = [NSMutableArray array];
for (NSDictionary *dict in myArray) {
[arr addObject:[[dict allValues] objectAtIndex:0]];
}
NSLog(#"%#",arr);
Note : Make sure you have only one value in each dictionary.
it will return
[
5 min,
15 min,
30 min,
1 hour
]
#johnyu's answers is technically correct, but I don't see any reason to include the secondary loop, especially if the data structure will remain the same.
NSArray *myArray = #[#{#300:#"5 min"},
#{#900:#"15 min"},
#{#1800:#"30 min"},
#{#3600:#"1 hour"}];
NSMutableArray *arrayOfValues = [NSMutableArray new];
NSMutableArray *arrayOfKeys = [NSMutableArray new];
for (NSDictionary *dictionary in myArray) {
[arrayOfValues addObject:dictionary.allValues[0]];
[arrayOfKeys addObject:dictionary.allKeys[0]];
}
NSLog(#"%#",arrayOfKeys);
NSLog(#"%#",arrayOfValues);
Try this:
NSArray *myArray = #[#{#300:#"5 min"},
#{#900:#"15 min"},
#{#1800:#"30 min"},
#{#3600:#"1 hour"}];
NSMutableArray *keyArray = [[NSMutableArray alloc] init];
NSMutableArray *valueArray = [[NSMutableArray alloc] init];
for (NSDictionary *dictionary in myArray) {
for (NSString *key in dictionary) {
[keyArray addObject:key];
[valueArray addObject:[dictionary objectForKey:key]];
}
}

# char as a key in NSDictionary

I tried using the # char as a key in a NSDictionary and my application simply crashes. I searched for "invalid" key names, could not find the #"#" anywhere. If I use something else than #"#" it all works fine.
I have a list of comanies, I get the first letter of each company and then I am creating a NSMutableDictionary entry containing the first letter as the key and a NSMutableArray as the value.
NSMutableDictionary indexDictionary = [[NSMutableDictionary alloc] init];
// here we have a loop on companyName
{
NSString *fristLetter = [[companyName substringToIndex:1] uppercaseString];
NSMutableArray *arrayOfIndexedCompanies = [indexDictionary valueForKey:firstLetter];
if (arrayOfIndexedCompanies) {
[arrayOfIndexedCompanies addObject:companyName]
}
else {
NSMutableArray *newArray = [NSMutableArray array];
[indexDictionary setObject:newArray forKey:firstLetter];
[newArray addObject:companyName];
}
}
I enabled breakpoint break on throw and it stops at the [indexDictionary valueForKey:firstLetter]... only when firstLetter is a #"#".
I had an if saying:
if ([firstLetter isEqualToString:#"#"]) {
firstLetter = #"A";
}
and this works fine, it places the # starting companies in the A section correctly. If I am letting the firstLetter unchanged (leaving it as #"#") the application will crash.
Also, this is not really my code, I am just trying to fix it, I am not quite familiar with ObjC and Foundation so please be gentle.
Read the documentation :)
Specifically, this bit :
If key does not start with “#”, invokes objectForKey:. If key does start with “#”, strips the “#” and invokes [super valueForKey:] with the rest of the key.
I guess that super valueForKey: isn't happy being called :)
To fix it, just call objectForKey: instead of valueForKey:
Using the string #"#" as a dictionary key works just fine:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:#"Test 1", #"#", #"Test 2", #"Another #", nil];
NSString *result = [dict objectForKey:#"#"];
NSLog(#"%#", result);
// --> Test 1
You could give a try with #"\u0040"

What's the real type? NSString or NSNumber

I have a NSDictionary that contains data converted from json data, like {"message_id":21}.
then I use NSNumber *message_id = [dictionary valueForKey:#"message_id"] to get the data.
but when I use this message_id,
Message *message = [NSEntityDescription ....
message.messageId = message_id;
I got the runtime error, assigning _NSCFString to NSNumber,
so I have to use NSNumberFormatter to do the conversion.
NSString *messageId = [dictionary valueForKey:#"message_id"];
NSNumberFormatter * f = [[NSNumberFormatter alloc] init];
[f setNumberStyle:NSNumberFormatterNoStyle];
message.messageId = [f numberFromString:messageId];
this code works.
but when I was debugging, I saw message_id of
NSNumber *message_id = [dictionary valueForKey:#"message_id"]
has a valid value, 21.
Can anyone see the problem here?
You are trying to save a NSString to a NSNumber. If you want it as an NSNumber you can do:
NSNumber *message_id = [NSNumber numberWithInt:[[dictionary valueForKey:#"message_id"] intValue]];
This should solve your problem.
What library are you using to do the conversion? {"message_id":21} means that an NSNumber with a value of 21 should be returned as an NSNumber, {"message_id":"21"} should return it as an NSString.
Using a number formatter is total overkill. Use the method "integerValue" which works just fine both with NSString* and with NSNumber* - you will get the integer 21, whether the object is NSString or NSNumber. The formatter code will obviously run into trouble if your object is an NSNumber and not an NSString.
So: message.messageId = [[NSNumber numberWithInteger:[messageId integerValue]];
I'd probably add a category to NSDictionary
(NSNumber*)nsIntegerNumberForKey:(NSString*)key
which handles the situations where the key is not present, or where the value is a null value or a dictionary or array, so you can use it everywhere you need an NSNumber with an integer value from a JSON document and have error checking everywhere.
Read here SAVING JSON TO CORE DATA and JSON official page
The JSON standard is quite clear about how to distinguish strings from
numbers– basically, strings are surrounded by quotes and numbers are
not. JSON web services however, are not always good about following this requirement. And even when they are, they are not always consistent from one record to another.
So if you have receive NSNumber where NSString is preferred, you must inspect and fix yourself

Difference between objectForKey and valueForKey?

What is the difference between objectForKey and valueForKey?
I looked both up in the documentation and they seemed the same to me.
objectForKey: is an NSDictionary method. An NSDictionary is a collection class similar to an NSArray, except instead of using indexes, it uses keys to differentiate between items. A key is an arbitrary string you provide. No two objects can have the same key (just as no two objects in an NSArray can have the same index).
valueForKey: is a KVC method. It works with ANY class. valueForKey: allows you to access a property using a string for its name. So for instance, if I have an Account class with a property accountNumber, I can do the following:
NSNumber *anAccountNumber = [NSNumber numberWithInt:12345];
Account *newAccount = [[Account alloc] init];
[newAccount setAccountNumber:anAccountNUmber];
NSNumber *anotherAccountNumber = [newAccount accountNumber];
Using KVC, I can access the property dynamically:
NSNumber *anAccountNumber = [NSNumber numberWithInt:12345];
Account *newAccount = [[Account alloc] init];
[newAccount setValue:anAccountNumber forKey:#"accountNumber"];
NSNumber *anotherAccountNumber = [newAccount valueForKey:#"accountNumber"];
Those are equivalent sets of statements.
I know you're thinking: wow, but sarcastically. KVC doesn't look all that useful. In fact, it looks "wordy". But when you want to change things at runtime, you can do lots of cool things that are much more difficult in other languages (but this is beyond the scope of your question).
If you want to learn more about KVC, there are many tutorials if you Google especially at Scott Stevenson's blog. You can also check out the NSKeyValueCoding Protocol Reference.
When you do valueForKey: you need to give it an NSString, whereas objectForKey: can take any NSObject subclass as a key. This is because for Key-Value Coding, the keys are always strings.
In fact, the documentation states that even when you give valueForKey: an NSString, it will invoke objectForKey: anyway unless the string starts with an #, in which case it invokes [super valueForKey:], which may call valueForUndefinedKey: which may raise an exception.
Here's a great reason to use objectForKey: wherever possible instead of valueForKey: - valueForKey: with an unknown key will throw NSUnknownKeyException saying "this class is not key value coding-compliant for the key ".
As said, the objectForKey: datatype is :(id)aKey whereas the valueForKey: datatype is :(NSString *)key.
For example:
NSDictionary *dict = [NSDictionary dictionaryWithObjectsAndKeys:[NSArray arrayWithObject:#"123"],[NSNumber numberWithInteger:5], nil];
NSLog(#"objectForKey : --- %#",[dict objectForKey:[NSNumber numberWithInteger:5]]);
//This will work fine and prints ( 123 )
NSLog(#"valueForKey : --- %#",[dict valueForKey:[NSNumber numberWithInteger:5]]);
//it gives warning "Incompatible pointer types sending 'NSNumber *' to parameter of type 'NSString *'" ---- This will crash on runtime.
So, valueForKey: will take only a string value and is a KVC method, whereas objectForKey: will take any type of object.
The value in objectForKey will be accessed by the same kind of object.
This table represents four differences between objectForKey and valueForKey.
objectForKey
valueForKey
Works on ...
NSDictionary
NSDictionary / KVC
Throws exception
No
Yes (on KVC)
Feed
NSObject's subclass
NSString
Usage on KVC
cannot
can
I'll try to provide a comprehensive answer here. Much of the points appear in other answers, but I found each answer incomplete, and some incorrect.
First and foremost, objectForKey: is an NSDictionary method, while valueForKey: is a KVC protocol method required of any KVC complaint class - including NSDictionary.
Furthermore, as #dreamlax wrote, documentation hints that NSDictionary implements its valueForKey: method USING its objectForKey: implementation. In other words - [NSDictionary valueForKey:] calls on [NSDictionary objectForKey:].
This implies, that valueForKey: can never be faster than objectForKey: (on the same input key) although thorough testing I've done imply about 5% to 15% difference, over billions of random access to a huge NSDictionary. In normal situations - the difference is negligible.
Next: KVC protocol only works with NSString * keys, hence valueForKey: will only accept an NSString * (or subclass) as key, whilst NSDictionary can work with other kinds of objects as keys - so that the "lower level" objectForKey: accepts any copy-able (NSCopying protocol compliant) object as key.
Last, NSDictionary's implementation of valueForKey: deviates from the standard behavior defined in KVC's documentation, and will NOT emit a NSUnknownKeyException for a key it can't find - unless this is a "special" key - one that begins with '#' - which usually means an "aggregation" function key (e.g. #"#sum, #"#avg"). Instead, it will simply return a nil when a key is not found in the NSDictionary - behaving the same as objectForKey:
Following is some test code to demonstrate and prove my notes.
- (void) dictionaryAccess {
NSLog(#"Value for Z:%#", [#{#"X":#(10), #"Y":#(20)} valueForKey:#"Z"]); // prints "Value for Z:(null)"
uint32_t testItemsCount = 1000000;
// create huge dictionary of numbers
NSMutableDictionary *d = [NSMutableDictionary dictionaryWithCapacity:testItemsCount];
for (long i=0; i<testItemsCount; ++i) {
// make new random key value pair:
NSString *key = [NSString stringWithFormat:#"K_%u",arc4random_uniform(testItemsCount)];
NSNumber *value = #(arc4random_uniform(testItemsCount));
[d setObject:value forKey:key];
}
// create huge set of random keys for testing.
NSMutableArray *keys = [NSMutableArray arrayWithCapacity:testItemsCount];
for (long i=0; i<testItemsCount; ++i) {
NSString *key = [NSString stringWithFormat:#"K_%u",arc4random_uniform(testItemsCount)];
[keys addObject:key];
}
NSDictionary *dict = [d copy];
NSTimeInterval vtotal = 0.0, ototal = 0.0;
NSDate *start;
NSTimeInterval elapsed;
for (int i = 0; i<10; i++) {
start = [NSDate date];
for (NSString *key in keys) {
id value = [dict valueForKey:key];
}
elapsed = [[NSDate date] timeIntervalSinceDate:start];
vtotal+=elapsed;
NSLog (#"reading %lu values off dictionary via valueForKey took: %10.4f seconds", keys.count, elapsed);
start = [NSDate date];
for (NSString *key in keys) {
id obj = [dict objectForKey:key];
}
elapsed = [[NSDate date] timeIntervalSinceDate:start];
ototal+=elapsed;
NSLog (#"reading %lu objects off dictionary via objectForKey took: %10.4f seconds", keys.count, elapsed);
}
NSString *slower = (vtotal > ototal) ? #"valueForKey" : #"objectForKey";
NSString *faster = (vtotal > ototal) ? #"objectForKey" : #"valueForKey";
NSLog (#"%# takes %3.1f percent longer then %#", slower, 100.0 * ABS(vtotal-ototal) / MAX(ototal,vtotal), faster);
}