开发者

how to use a NSDecimalNumber object value in a different function?

开发者 https://www.devze.com 2023-02-22 14:08 出处:网络
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.

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. I want to use th开发者_StackOverflowat 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. EG, your first method can just be

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:

@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.

0

精彩评论

暂无评论...
验证码 换一张
取 消