2013-11-03 88 views
1

我一直在想如何更改NSNumber的值,這些NSNumber是存儲在NSMutableDictionary中的。我不得不使用NSNumber,因爲只有對象可以存儲在NSDictionary中。這是我現在所擁有的,並不像我預期的那樣。在NSMutableDictionary中更改NSNumber的值

int newInt = [self.myDict[@"key"] intValue] + 100; 
    NSLog(@"%d",newInt); 
    [self.myDict setObject:@(newInt) forKey:@"key"]; 
    NSLog(@"%d",[self.myDict[@"key"] intValue]); 

第一次NSLog按預期打印100,但第二次打印0.我應該如何更改該字典中的NSNumber的值?謝謝您的幫助!

+2

被'self.myDict'初始化? – Sebastian

+0

這應該工作。你有沒有登錄self.myDict,以確保它不是零? – rdelmar

回答

2

答案是self.myDict是零。記錄下來,你會看到。

1

您需要:self.myDict = [NSMutableDictionary new];在設定值之前。

實施例:

@interface AppDelegate() 
@property (nonatomic, strong) NSMutableDictionary *myDict; 
@end 

@implementation AppDelegate 
- (void)applicationDidFinishLaunching:(NSNotification *)aNotification { 
    self.myDict = [NSMutableDictionary new]; 

    int newInt = [self.myDict[@"key"] intValue] + 100; 
    NSLog(@"%d",newInt); 
    [self.myDict setObject:@(newInt) forKey:@"key"]; 
    NSLog(@"%d",[self.myDict[@"key"] intValue]); 
} 
相關問題