简体   繁体   English

如何在不同的函数中使用NSDecimalNumber对象值?

[英]how to use a NSDecimalNumber object value in a different function?

I'm new to objective and I wanted to know how to do this. 我是客观的新手,我想知道如何做到这一点。

I have a function where I do some calculation and store the result in a NSDecimalNumber object. 我有一个函数,在其中进行一些计算并将结果存储在NSDecimalNumber对象中。 I want to use that result in a different function.can anyone help me! 我想将结果用于其他功能。有人可以帮助我! thanks! 谢谢!

Example: 例:

- (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; 

}

If you're setting the variable like that, you don't need to call alloc/init first. 如果要像这样设置变量,则无需先调用alloc / init。 EG, your first method can just be EG,您的第一种方法就是

NSDecimalNumber *one = [[NSDecimalNumber alloc]initWithString:@"1"];
NSDecimalNumber *two = [[NSDecimalNumber alloc]initWithString:@"2"];    
result = [one decimalNumberByAdding:two];

Assuming, that is, that you've declared result before as in: 假设,也就是说,您之前已经声明了result,如下所示:

@interface MyClass {
NSDecimalNumber *result;
}

Then, in your second function, if you really need a copy of result instead of just referring to the result variable itself, you could do: 然后,在第二个函数中,如果确实需要结果的副本,而不仅仅是引用结果变量本身,则可以执行以下操作:

NSDecimalNumber *findNumber = [result copy];

Remember to release when you're done. 完成后记得释放。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM