Reputation: 3
I am new to this site, and also to iphone development. I am learning Objective-C through a few different books and through a Stanford University iOS development online class.
The current project is to build a calculator (already done), but now we have to add an array that keeps track of each operand or operation pressed. I tried to do this by adding a section of code with the "operationPressed" method and the "setOperand" method, but nothing gets added to the array.
In my .h file I declared an instance variable of NSMutableArray *internalExpression and this is the code for my .m file
- (void) setOperand: (double) anOperand
{
operand = anoperand;
NSNumber *currentOperand = [NSNumber numberWithFloat:operand];
[internalExpression addObject:currentOperand];
}
The set operand works, and currentOperand gets set correctly (checked using NSLog) yet nothing every gets added to the NSMutableArray (also checked using NSLog and the array count method).
What am I missing??
Thanks!
Upvotes: 0
Views: 271
Reputation: 961
if in your header file there's a property declared like this:
@property (nonatomic, retain) NSMutableArray *internalExpression; // non ARC
or
@property (nonatomic, strong) NSMutableArray *internalExpression; // ARC
you have to initialize your property with an allocated object:
NSMutableArray *myMutableArray = [[NSMutableArray alloc] init];
[self setInternalExpression:myMutableArray];
[myMutableArray release]; // this line only if you're not using ARC.
If it's only an instance variable you just have to do it directly:
_internalExpression = [[NSMutableArray alloc] init];
And remember, if you're not using ARC, to release the object when you're done with it, or in the dealloc method of the Class.
Regards.
Upvotes: 2
Reputation: 10182
Declaring the NSMutableArray isn't enough, it has to be instantiated also. Add this line before the addObject:
call.
if(internalExpression == nil) internalExpression = [NSMutableArray array];
Upvotes: 0