无法正确读取NSNumber

时间:2015-02-20 18:24:06

标签: ios objective-c macos cocoa nsnumber

我试图回读我写给NSNumberNSUserDefaults24)的两个39993值。我可以很好地写出这些值,但是读取它会产生与预期完全不同的值。如果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部分做错了什么吗?感谢。

1 个答案:

答案 0 :(得分:2)

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

DO

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

或留在对象世界

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