我有一个NSMutableDictionary
,它在键/值配对中包含多个项目。我已经使用密钥存储了字符串并且没有问题地检索它们,但是,当我存储类型NSUInteger
的值并尝试从字典中取回时,我最终会得到一个非常大的值。
我的if语句的第一部分我检查我要查找的值是不是null还是大于零。我试图基本上在字典中保存我可以访问的分数或值,以便我可以添加或删除。
正如你在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"]);
}
}
答案 0 :(得分:2)
这看起来像一个问题:
currentTotal = (int)[appDelegate.data valueForKey:@"Total"];
-valueForKey:
返回指向Objective-C对象的指针,而不是int
,因此您无法将其转换为int
并期望发生任何有用的事情。如果它是NSNumber
,那么您需要执行以下操作:
currentTotal = [[appDelegate.data valueForKey:@"Total"] intValue];
有关详细信息,请参阅the docs on NSNumber
。