NSDictionary With Integer Values

牧云@^-^@ 提交于 2019-12-03 22:31:18
  1. You can only store objects, not primitives, within Cocoa collection classes, so to store numbers you need to use NSNumber objects.
  2. You need to use an NSMutableDictionary if you wish to change the contents later.
  3. Your call to dictionaryWithObjectsAndKeys has the keys and values reversed.
  4. Your stats object is not being retained, so it will be released next time round the run loop (if you're using manual reference counting, that is).

You want:

stats = [[NSMutableDictionary dictionaryWithObjectsAndKeys:
    [NSNumber numberWithInt:0], @"Attack",
    [NSNumber numberWithInt:0], @"Defense",
    [NSNumber numberWithInt:0], @"Special Attack",
    [NSNumber numberWithInt:0], @"Special Defense",
    [NSNumber numberWithInt:0], @"HP",
    nil] retain];

In order to change the values you need to create a new NSNumber object as they are immutable, so something like:

NSNumber *num = [stats objectForKey:@"Attack"];
NSNumber *newNum = [NSNumber numberWithInt:[num intValue] + (level * 5)];
[stats setObject:newNum forKey:@"Attack"];

All pretty tedious if you ask me; there must be an easier way, for example how about creating an Objective-C class to store and manipulate this stuff?

NSDictionarys store NSObject*s. In order to use them with integer values, you unfortunately need to use something like NSNumber. So your initialization would look like:

-(id) init {
    self = [super init];
    if(self) {
        stats = [NSDictionary dictionaryWithObjectsAndKeys:
              @"Attack",  [NSNumber numberWithInt:0],
              @"Defense", [NSNumber numberWithInt:0],
              @"Special Attack", [NSNumber numberWithInt:0],
              @"Special Defense", [NSNumber numberWithInt:0],
              @"HP", [NSNumber numberWithInt:0], nil];
    }
    return self;
}

Then you would have to retrieve them as numbers:

NSNumber *atk = [self.stats objectForKey:@"Attack"];
int iAtk = [atk intValue];
[self.stats setObject:[NSNumber numberWithInt:iAtk] forKey:@"Attack"];

EDIT

Of course, in order to do this, self.stats needs to be an NSMutableDictionary

Adapting @trojanfoe's answer for modern Objective-C with nice syntax sugar:

stats = [@{@"Attack"          : @0,
           @"Defense"         : @0,
           @"Special Attack"  : @0,
           @"Special Defense" : @0,
           @"HP"              : @0} mutableCopy];

And to update a value:

stats[@"Attack"] = @([stats[@"Attack"] intValue] + (level * 5));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!