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.
精彩评论