我是客观的新手,我想知道如何做到这一点。
我有一个函数,我在那里进行一些计算并将结果存储在NSDecimalNumber对象中。 我想在不同的函数中使用该结果。任何人都可以帮助我!谢谢!
示例:
- (IBAction)calculate:(id)sender{
NSDecimalNumber *one = [[NSDecimalNumber alloc]initWithString:@"1"];
NSDecimalNumber *two = [[NSDecimalNumber alloc]initWithString:@"2"];
//result is a NSDecimalNumber object created in my .h file
result = [[NSDecimalNumber alloc]init];
result = [one decimalNumberByAdding:two];
//result is now equal to 3
}
- (IBAction)findResult:(id)sender{
NSDecimalNumber *findNumber = [[NSDecimalNumber alloc]init];
//I want "findNumber" to have the same value as result, which was given the value of 3 in method calculate
findNumber = result;
}
答案 0 :(得分:1)
如果您正在设置这样的变量,则不需要先调用alloc / init。 EG,你的第一种方法可以就是
NSDecimalNumber *one = [[NSDecimalNumber alloc]initWithString:@"1"];
NSDecimalNumber *two = [[NSDecimalNumber alloc]initWithString:@"2"];
result = [one decimalNumberByAdding:two];
假设,您已经在之前声明了结果:
@interface MyClass {
NSDecimalNumber *result;
}
然后,在你的第二个函数中,如果你真的需要结果的副本而不是仅仅引用结果变量本身,你可以这样做:
NSDecimalNumber *findNumber = [result copy];
记得在完成后发布。