How to increment a NSNumber

前端 未结 9 1239
情书的邮戳
情书的邮戳 2020-12-13 01:47

How do I increment a NSNumber?

i.e. myNSNumber++

9条回答
  •  时光说笑
    2020-12-13 02:28

    Lots of good info in the answers to this question. I used the selected answer in my code and it worked. Then I started reading the rest of the posts and simplified the code a lot. It’s a bit harder to read if you aren’t familiar with the changes in notation that were introduced in Xcode 5, but it’s a lot cleaner. I probably could make it just one line, but then it’s a little too hard to figure out what I’m doing.

    I’m storing an NSNumber in a dictionary and I want to increment it. I get it, convert it to an int, increment it while converting it to an NSNumber, then put it back into the dictionary.

    Old Code

     NSNumber *correct = [scoringDictionary objectForKey:@"correct"];
     int correctValue = [correct intValue];
     correct = [NSNumber numberWithInt:correctValue + 1];
     [scoringDictionary removeObjectForKey:@"correct"];
     scoringDictionary[@"correct"] = correct;
    

    New code

    NSNumber *correct = [scoringDictionary objectForKey:@"correct"];
    scoringDictionary[@"correct"] = @(correct.intValue + 1);
    

提交回复
热议问题