1

I want to use a UIView tag as the key for an NSMutableDictionary. However, the compiler objects to me using an NSInteger as a key. I want to do the following:

NSInteger elementKey = _viewBeingDragged.tag;
myClass* element = [_model.elements objectForKey:elementKey];

How can I use elementKey as my dictionary key?

Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
whatdoesitallmean
  • 1,586
  • 3
  • 18
  • 40
  • This question has been answered here: http://stackoverflow.com/questions/2992315/uiview-as-dictionary-key – gvaish Aug 02 '16 at 22:18

5 Answers5

2

A NSInteger is not an object, and cannot be used as a key. You can wrap it in a NSNumber instead:

NSNumber* elementKey = [NSNumber numberWithInt:_viewBeingDragged.tag];
myClass* element = [_model.elements objectForKey:elementKey];
Evan Mulawski
  • 54,662
  • 15
  • 117
  • 144
0
NSNumber* elementKey = [NSNumber numberWithInt:_viewBeingDragged.tag];
unexpectedvalue
  • 6,079
  • 3
  • 38
  • 62
0

I agree with both @Mario and @EvanMulawski but I prefer using strings for my key. Oh, and as for the reason that the compiler rejects the use of an NSInteger is that NSIntegers are pretty much equivalent to long ints.

NSString* elementKey = [NSString stringWithFormat:@"%i",_viewBeingDragged.tag];
//or NSNumber* elementKey = [NSNumber numberWithInt:_viewBeingDragged.tag];
myClass* element = [_model.elements objectForKey:elementKey];
erran
  • 1,300
  • 2
  • 15
  • 36
0

Wrap it in an NSNumber literal.

myClass* element = _model.elements[@(_viewBeingDragged.tag)];

And assignment:

NSInteger tag = view.tag;
myClass *value;
_model.elements[@(tag)] = value;
kkodev
  • 2,557
  • 23
  • 23
-3

Rather create an NSString for the key, although you could use any NSCopying conform object:

NSString *key = [NSString stringWithFormat: @"%d",elementKey];
erran
  • 1,300
  • 2
  • 15
  • 36
Mario
  • 4,530
  • 1
  • 21
  • 32
  • 1
    Your code snippet is incorrect, since you aren't passing an argument to match the "%d" format specifier. Also, using a string as a key when `NSNumber` would be a more natural fit is a bad idea and potentially unsafe. For example, for 64-bit, "%d" is not the right specifier for `NSInteger`, so you could get the same string for two different tags. – Ken Thomases Jun 09 '12 at 11:36