我有一个NSMutableDictionary
在键/值对中保存多个项目的。我已经用一个键存储了字符串并且没有问题地检索它们,但是,当我存储一个类型的值NSUInteger
并尝试从字典中取回它时,我最终得到了一个非常大的值。
if 语句的第一部分我检查我要查找的值是否不为空或大于零。我试图基本上在字典中保存一个我可以访问的分数或值,以便我可以添加或删除。
正如您在 else 语句中看到的那样,我有两个NSLog
语句,这就是我看到值差异的地方。第一NSLog
条语句显示的值为 100,正如我希望单击我的“快乐”按钮时所期望的那样。但是,一旦从字典中检索到该值,currentTotal 就是 109709424。我确信这与我在将此整数值转换为字符串时使用的格式说明符有关。我尝试将此值 currentTotal 作为 int 或 NSUInteger 存储在我的字典中的键“Total”下,但是在 ARC 中不允许从非 Objective-c 类型对象转换为“id”,所以我被卡住了。
NSUInteger currentTotal = 0;
NSUInteger happinessValue = 100;
NSUInteger sadnessValue = 20;
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];
if ([appDelegate.data valueForKey:@"Total"] != nil || [appDelegate.data valueForKey:@"Total"] > 0) {
currentTotal = (int)[appDelegate.data valueForKey:@"Total"];
if ([segue.identifier isEqualToString:@"Happy"]) {
[segue.destinationViewController setHappiness:(int)happinessValue :segue.identifier];
currentTotal = add(currentTotal, happinessValue);
[appDelegate.data setObject:(NSString *)[NSString stringWithFormat: @"Value: %i", happinessValue] forKey:@"Value"];
} else if ([segue.identifier isEqualToString:@"Sad"]) {
[segue.destinationViewController setHappiness:(int)sadnessValue :segue.identifier];
currentTotal -= [segue.destinationViewController setTotalValue:happinessValue];
[appDelegate.data setObject:(NSString *)[NSString stringWithFormat: @"Value: %i", sadnessValue] forKey:@"Value"];
}
}
else {
if ([segue.identifier isEqualToString:@"Happy"]) {
[segue.destinationViewController setHappiness:(int)happinessValue :segue.identifier];
NSLog(@"Old value ELSE: %i", currentTotal);
currentTotal = [segue.destinationViewController setTotalValue:happinessValue];
NSLog(@"New value ELSE: %i", currentTotal);
[appDelegate.data setObject:(NSString *)[NSString stringWithFormat: @"Value: %i", happinessValue] forKey:@"Value"];
} else if ([segue.identifier isEqualToString:@"Sad"]) {
[segue.destinationViewController setHappiness:(int)sadnessValue :segue.identifier];
currentTotal = [segue.destinationViewController setTotalValue:happinessValue];
[appDelegate.data setObject:(NSString *)[NSString stringWithFormat: @"Value: %i", sadnessValue] forKey:@"Value"];
}
NSLog(@"Current Total: %i", currentTotal);
[appDelegate.data setObject:[NSString stringWithFormat:@"%d", currentTotal] forKey:@"Total"];
NSLog(@"Total stored: %i", (int)[appDelegate.data valueForKey:@"Total"]);
}
}