[英]Issue with value conversion in iOS using NSUInteger and NSMutableDictionary
我有一个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"]);
}
}
这看起来像一个问题:
currentTotal = (int)[appDelegate.data valueForKey:@"Total"];
-valueForKey:
返回指向Objective-C对象的指针,而不是int
,因此您无法将其-valueForKey:
转换为int
并期望发生任何有用的事情。 如果它是NSNumber
,那么你需要做这样的事情:
currentTotal = [[appDelegate.data valueForKey:@"Total"] intValue];
有关更多信息,请参阅NSNumber
上的文档 。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.