我有一个 NSMutableDictionary
,它以键/值对的形式包含多个项目。我用一个键存储了字符串并毫无问题地检索了它们,但是,当我存储类型为 NSUInteger
的值并尝试从字典中取回它时,我最终得到了一个非常大的值。
我的 if 语句的第一部分检查我要查找的值是否不为空或大于零。我试图基本上在我可以访问的字典中保留一个分数或值,以便我可以添加或删除。
正如您在 else 语句中看到的,我有两个 NSLog
语句,这是我看到值差异的地方。第一个 NSLog
语句显示值 100,正如我希望通过单击“Happy”按钮。但是,一旦从字典中检索回该值,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"]);
}
}
最佳答案
这看起来像个问题:
currentTotal = (int)[appDelegate.data valueForKey:@"Total"];
-valueForKey:
返回指向 Objective-C 对象的指针,而不是 int
,因此您不能将其转换为 int
并且期待任何有用的事情发生。如果它是一个 NSNumber
,那么你需要做这样的事情:
currentTotal = [[appDelegate.data valueForKey:@"Total"] intValue];
参见 the docs on NSNumber
获取更多信息。
关于ios - iOS 中使用 NSUInteger 和 NSMutableDictionary 的值转换问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11057994/