Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to Properly set an integer value in NSDictionary?

Tags:

objective-c

The following code snippet:

NSLog(@"userInfo: The timer is %d", timerCounter);

NSDictionary *dict = [NSDictionary dictionaryWithObject:[NSNumber numberWithInteger:timerCounter] forKey:@"timerCounter"];

NSUInteger c = (NSUInteger)[dict objectForKey:@"timerCounter"];
NSLog(@"userInfo: Timer started on %d", c);

produces output along the lines of:

2009-10-22 00:36:55.927 TimerHacking[2457:20b] userInfo: The timer is 1
2009-10-22 00:36:55.928 TimerHacking[2457:20b] userInfo: Timer started on 5295968

(FWIW, timerCounter is a NSUInteger.)

I'm sure I'm missing something fairly obvious, just not sure what it is.

like image 953
Bill Avatar asked Oct 22 '09 05:10

Bill


People also ask

How do you set a value in NSDictionary?

You have to convert NSDictionary to NSMutableDictionary . You have to user NSMutableDictionary in place of the NSDictionary . After that you can able to change value in NSMutableDictionary . Save this answer.

How do you add value in NSMutableDictionary?

[myDictionary setObject:nextValue forKey:myWord]; You can simply say: myDictionary[myWord] = nextValue; Similarly, to get a value, you can use myDictionary[key] to get the value (or nil).

What is NSDictionary in Swift?

An object representing a static collection of key-value pairs, for use instead of a Dictionary constant in cases that require reference semantics.


2 Answers

You should use intValue from the received object (an NSNumber), and not use a cast:

NSUInteger c = [[dict objectForKey:@"timerCounter"] intValue];
like image 112
epatel Avatar answered Oct 30 '22 17:10

epatel


Dictionaries always store objects. NSInteger and NSUInteger are not objects. Your dictionary is storing an NSNumber (remember that [NSNumber numberWithInteger:timerCounter]?), which is an object. So as epatel said, you need to ask the NSNumber for its unsignedIntegerValue if you want an NSUInteger.

like image 37
Chuck Avatar answered Oct 30 '22 16:10

Chuck