无法正确读取 NSNumber

Unable to read NSNumber correctly

我正在尝试读回我写入 NSUserDefaults 的两个 NSNumber 值(2439993)。我可以很好地写出这些值,但读回它会给出与预期完全不同的值。如果 NSNumber 能够被正确读取,我想将其转换为 UInt32 原来的样子。

- (void)applicationDidFinishLaunching:(NSNotification *)aNotification {
    [self writeDefaults];
    [self readDefaults];
}

- (void)writeDefaults {

    UInt32 val1 = 24;
    UInt32 val2 = 39993;

    NSNumber* value1 = [NSNumber numberWithUnsignedInteger:val1];
    NSNumber* value2 = [NSNumber numberWithUnsignedInt:val2];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    [defaults setObject:value1 forKey:@"value1"]; // saves 24
    [defaults setObject:value2 forKey:@"value2"]; // saves 39993

    NSLog(@"value1: %@",value1); // outputs 24
    NSLog(@"value2: %@",value2); // outputs 39993

    [[NSUserDefaults standardUserDefaults] synchronize];
}

- (void)readDefaults {

    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];

    NSNumber *val1 = [defaults valueForKey:@"value1"];
    NSNumber *val2 = [defaults valueForKey:@"value2"];

    NSLog(@"val1: %u",(unsigned int)val1); // outputs 6199
    NSLog(@"val2: %u",(unsigned int)val2); // outputs 10238263
}
@end

知道我在 readDefaults 部分做错了什么吗?谢谢。

您正在打印 NSNumber 对象的指针内存地址

NSLog(@"val1: %lu",[val1 unsignedIntegerValue]);
NSLog(@"val2: %lu",[val2 unsignedIntegerValue]);

或者留在对象世界

NSLog(@"val1: %@",val1);
NSLog(@"val2: %@",val2);