-2

我需要存储一个十进制数,而字符串、int 或数字似乎都不能满足我的要求。我不能使用 NSNumber,因为我需要稍后才能更改它。

我搜索了整个互联网,但我似乎无法找到它。

答案可能很简单。

谢谢!

更新:

这里有一些数据

循环代码{

nslog(保存号码);

保存号码 3.1415926535;

删除所有已存储的数据

//现在字符串不再存在 }

我需要能够将该数字保存在“此处的某种数据”中的循环之外,因为当循环开始时,从循环创建的所有内容都将被删除。

4

3 回答 3

1

Try using NSNumber like so:

double myValue = 20.0;

NSNumber* number = [NSNumber numberWithDouble:myValue];

// Do something with NSNumber like write it to disk, put it in an array, dictionary whatever ....

// Then pull it back out
double myOldValue = [number doubleValue];

To pull a double value out after the app has been closed (I'm interpreting that to mean "backgrounded" or "suspended"), try writing it to NSUserDefaults before the app is backgrounded and then pull it back out when your app resumes.

// Write a double to NSUserDefaults
[[NSUserDefaults standardUserDefaults] setDouble:myValue forKey:@"myDoubleValue"];

// Write an NSNumber to NSUserDefaults
[[NSUserDefaults standardUserDefaults] setObject:number forKey:@"myNumberWithDoubleValue"];

// Extract double from NSUserDefaults
double myReallyOldDoubleValue = [[NSUserDefaults standardUserDefaults] doubleForKey:@"myDoubleValue"];

// Extract NSNumber from NSUserDefaults
NSNumber* myReallyOldNumberValue = [[NSUserDefaults standardUserDefaults] objectForKey:@"myNumberWithDoubleValue"];

Or in your psuedo code:

NSNumber *someValue = [NSNumber numberWithDouble:0.0];

some kind of data here
looping code {

    nslog(save number)

    someValue = [NSNumber numberWithDouble:3.1412];

    delete all data that has been stored
}

Store a pointer to your number or a instance variable or class property

于 2013-04-30T21:30:21.780 回答
0

可以使用NSNumber,或者是十进制的子类NSDecimalNumber。仅仅因为对象本身是不可变的,并不意味着您不能更改给定变量指向的值。例如:

NSDecimalNumber *a = [NSDecimalNumber numberWithInt:2];
a = [a decimalNumberByAdding:[NSDecimalNumber numberWithInt:12]];
a = [a decimalNumberByDividing:[NSDecimalNumber numberWithDouble:2.3]];

这就像真正的整数一样,它们也是不可变的。

double a = 2;
a = a + 12;
a = a / 2.3;

话虽这么说,但NSDecimalNumber很冗长。如果您可以摆脱原始类型(例如,以美分而不是美元进行计算),那可能会更好。

于 2013-04-30T21:36:45.997 回答
-1

Just use a double. When it comes time to store it, you can get a number like this:

NSNumber *number = @(myDouble);

To change an NSNumber into a double,

double myDouble = [number doubleValue];
于 2013-04-30T21:30:29.323 回答