Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Adding negative NSNumber value to a NSDictionary

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?

like image 762
falc03 Avatar asked Jan 27 '26 11:01

falc03


2 Answers

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.

like image 103
Conrad Shultz Avatar answered Jan 29 '26 12:01

Conrad Shultz


@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
like image 28
jonkroll Avatar answered Jan 29 '26 12:01

jonkroll



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!