简体   繁体   中英

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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