Using a property as a count in Objective C - objective-c

I am new to Objective C. I was following Stanford lectures 2011-12 fall on iOS development and in assignment 1 it asks to implement a decimal point in a calculator. This is what my implementation looks like:
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
#interface CalculatorViewController()
#property (nonatomic) BOOL userIsInTheMiddleOfEnteringNumber;
#property (nonatomic,strong) CalculatorBrain *brain;
#property (nonatomic) int userPressedDecimalPoint;
#end
#implementation CalculatorViewController
#synthesize display = _display;
#synthesize userIsInTheMiddleOfEnteringNumber = _userIsInTheMiddleOfEnteringNumber;
#synthesize userPressedDecimalPoint = _userPressedDecimalPoint;
#synthesize brain = _brain;
- (CalculatorBrain *) brain{
if (!_brain) _brain = [[CalculatorBrain alloc] init];
return _brain;
}
- (IBAction)digitpressed:(UIButton *)sender {
NSString *digit = sender.currentTitle;
if (digit == #"."){
self.userIsInTheMiddleOfEnteringNumber = YES;
self.userPressedDecimalPoint++;
}
if (self.userIsInTheMiddleOfEnteringNumber && self.userPressedDecimalPoint< 2){
self.display.text = [self.display.text stringByAppendingString:digit];
NSLog(#"decimal pressed: %d times",self.userPressedDecimalPoint);
}
else{
self.display.text = digit;
self.userIsInTheMiddleOfEnteringNumber = YES;
self.userPressedDecimalPoint = 1;
}
}
So basically I have setup a property userPressedDecimalPoint and i try to use this property as a counter every time the decimal point is pressed. However from the NSLog i see that no matter how many times i press the decimal point it only shows 1 time pressed. Consequently, the output shows multiple decimal points if entered. Any suggestions would be appreciated. Thanks!
Full version of Corrected Code:
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
#interface CalculatorViewController()
#property (nonatomic) BOOL userIsInTheMiddleOfEnteringNumber;
#property (nonatomic,strong) CalculatorBrain *brain;
#property (nonatomic) int userPressedDecimalPoint;
#end
#implementation CalculatorViewController
#synthesize display = _display;
#synthesize userIsInTheMiddleOfEnteringNumber = _userIsInTheMiddleOfEnteringNumber;
#synthesize userPressedDecimalPoint = _userPressedDecimalPoint;
#synthesize brain = _brain;
- (CalculatorBrain *) brain{
if (!_brain) _brain = [[CalculatorBrain alloc] init];
return _brain;
}
- (IBAction)digitpressed:(UIButton *)sender {
NSString *digit = sender.currentTitle;
if ([digit isEqualToString:#"."]){
self.userIsInTheMiddleOfEnteringNumber = YES;
self.userPressedDecimalPoint++;
}
if (self.userIsInTheMiddleOfEnteringNumber && self.userPressedDecimalPoint< 2){
self.display.text = [self.display.text stringByAppendingString:digit];
// NSLog(#"decimal pressed: %d times",self.userPressedDecimalPoint);
}
else if (![digit isEqualToString:#"."]){
self.display.text = digit;
self.userIsInTheMiddleOfEnteringNumber = YES;
}
}
- (IBAction)operationPressed:(UIButton *)sender {
if (self.userIsInTheMiddleOfEnteringNumber) [self enterPressed];
double result = [self.brain performOperation:sender.currentTitle];
NSString *resultString = [NSString stringWithFormat:#"%g", result];
self.display.text = resultString;
}
- (IBAction)enterPressed {
self.userPressedDecimalPoint = 0;
[self.brain pushOperand:[self.display.text doubleValue]];
self.userIsInTheMiddleOfEnteringNumber = NO;
}
#end

Unless there is something that sets userIsInTheMiddleOfEnteringNumber to NO, any time the number is greater than one, your code will execute self.userPressedDecimalPoint = 1; and set it back to one.

Related

objective c delegates

My program displays images with a timer. I want the user to be able to adjust the timer by using a UISlider.
I have a Deck class, which delegates and listens to another delegate 'SpeedSliderDelegate'. I want my Deck class to listen for changes from the SpeedSliderDelegate and update a value.
How do I set my Deck.m model to listen to SpeedSliderDelegate...(just after if(self = [super init] in Deck.m)
SpeedSliderDelegate.h
#protocol SpeedSliderDelegate <NSObject>
-(void)setSpeed:(float)currentSpeed;
#end
Deck.h
#import "SpeedSliderDelegate.h"
#import <Foundation/Foundation.h>
#import "Card.h"
#protocol DeckLooperDelegate <NSObject>
-(void)cardHasChangedTo:card1 aCard2:(Card *)card2 totalCount:(NSInteger)totalCount stopTimer:(NSTimer*)stopTimer cards:(NSArray *)cards;
#end
#interface Deck : NSObject <SpeedSliderDelegate>
#property (nonatomic, retain)NSMutableArray *cards;
#property (nonatomic, retain)NSTimer *timer;
#property (nonatomic, retain)id <DeckLooperDelegate> delegate;
#property (nonatomic)NSInteger total;
#property (nonatomic) float testSpeed;
- (NSInteger) cardsRemaining;
- (void) startTimerLoop;
#end
Deck.m
#import "Deck.h"
#import "Card.h"
#implementation Deck
#synthesize cards;
#synthesize timer;
#synthesize delegate;
#synthesize total, testSpeed;
- (id) init
{
if(self = [super init])
{
//self.delegate = self something like this...
cards = [[NSMutableArray alloc] init];
NSInteger aCount, picNum = 0;
for(int suit = 0; suit < 4; suit++)
{
for(int face = 1; face < 14; face++, picNum++)
{
if (face > 1 && face < 7)
aCount = 1;
else if (face > 6 && face < 10)
aCount = 0;
else
aCount = -1;
NSString* imagePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:#"card_%d", picNum] ofType:#"png"];
UIImage* theImage = [[UIImage alloc] initWithContentsOfFile:imagePath];
Card *card = [[Card alloc] initWithFaceValue:(NSInteger)face
countValue:(NSInteger)aCount
suit:(Suit)suit
cardImage:(UIImage *)theImage];
[cards addObject:card];
}
}
}
return self;
}
-(void)setSpeed:(float)currentSpeed
{
testSpeed = currentSpeed;
}
-(void)startTimerLoop
{
if (!timer)
{
timer = [NSTimer scheduledTimerWithTimeInterval:testSpeed target:self
selector:#selector(timerEvent:) userInfo:nil repeats:YES ];
NSLog(#"Timer started!!!");
}
}
-(void)timerEvent:(NSTimer*)timer
{
srand(time(nil));
int index = rand()%[cards count];
Card *randomCard =[cards objectAtIndex:index];
[cards removeObjectAtIndex:index];
NSLog(#"%#" ,randomCard);
int index1 = rand()%[cards count];
Card *randomCard1 =[cards objectAtIndex:index1];
[cards removeObjectAtIndex:index1];
NSLog(#"%#" ,randomCard1);
total += (randomCard.countValue + randomCard1.countValue);
[self.delegate cardHasChangedTo:randomCard aCard2:randomCard1 totalCount:total stopTimer:self.timer cards:cards];
if ([cards count] == 0)
{
[self.timer invalidate];
self.timer = nil;
}
}
- (NSInteger) cardsRemaining
{
return [cards count];
}
- (NSString *) description
{
NSString *desc = [NSString stringWithFormat:#"Deck with %d cards\n",
[self cardsRemaining]];
return desc;
}
#end
GameViewController.h
#import "Deck.h"
#import "SpeedSliderDelegate.h"
#interface GameViewController : UIViewController <DeckLooperDelegate>
#property (nonatomic, retain) IBOutlet UIImageView *cardDisplay, *cardDisplay1;
#property (weak, nonatomic) IBOutlet UILabel *cardName, *cardName1;
#property (weak, nonatomic) IBOutlet UILabel *cardCount, *cardCount1;
#property (weak, nonatomic) IBOutlet UILabel *totalCount;
#property (nonatomic)int stop1;
#property (weak, nonatomic) IBOutlet UIButton *stopButton;
#property (weak, nonatomic) IBOutlet UIButton *restartButton;
#property (weak, nonatomic) IBOutlet UIButton *homeButton;
#property (weak, nonatomic) IBOutlet UISlider *speed;
#property (nonatomic, retain) id <SpeedSliderDelegate> delegate;
- (IBAction)start:(id)sender;
- (IBAction)stop:(id)sender;
- (IBAction)hideShow:(id)sender;
- (IBAction)homeAction:(id)sender;
#end
GameViewController.m
#import <QuartzCore/QuartzCore.h>
#import "GameViewController.h"
#import "Deck.h"
#implementation GameViewController
#synthesize cardDisplay, cardDisplay1, cardName, cardName1, cardCount, cardCount1, totalCount, stop1, stopButton, restartButton, homeButton, speed, delegate;
- (void)viewDidLoad
{
[super viewDidLoad];
Deck *deck = [[Deck alloc]init];
NSLog(#"%#", deck);
for (id cards in deck.cards)
{
NSLog(#"%#", cards);
}
deck.delegate = self;
[deck startTimerLoop];
cardDisplay.layer.cornerRadius = 7;
cardDisplay.clipsToBounds = YES;
cardDisplay1.layer.cornerRadius = 7;
cardDisplay1.clipsToBounds = YES;
[restartButton setHidden:YES];
[delegate setSpeed:speed.value];
}
//#pragma mark - DeckDelegate
-(void)cardHasChangedTo:(Card *)card1 aCard2:(Card *)card2 totalCount:(NSInteger)totalC stopTimer:(NSTimer *)stopTimer cards:(NSArray *)cards
{
[self.cardDisplay setImage:card1.cardImage];
[self.cardDisplay1 setImage:card2.cardImage];
self.cardName.text = card1.description;
self.cardName1.text = card2.description;
self.cardCount.text = [NSString stringWithFormat:#"%d", card1.countValue];
self.cardCount1.text = [NSString stringWithFormat:#"%d", card2.countValue];
self.totalCount.text = [NSString stringWithFormat:#"%d", totalC];
if (stop1 == 86)
{
[stopTimer invalidate];
stopTimer = nil;
}
if ([cards count] == 0)
{
[restartButton setHidden:NO];
}
}
- (IBAction)start:(id)sender
{
stop1 = 85;
[cardDisplay setHidden:YES];
[cardDisplay1 setHidden:YES];
self.totalCount.text = #"0";
self.cardCount.text = #"0";
self.cardCount1.text = #"0";
self.cardName.text = #"";
self.cardName1.text = #"";
Deck *deck = [[Deck alloc]init];
[NSTimer scheduledTimerWithTimeInterval:2 target:self
selector:#selector(cardDisplayDelay:) userInfo:nil repeats:NO];
NSLog(#"%#", deck);
deck.delegate = self;
[deck startTimerLoop];
cardDisplay.layer.cornerRadius = 7;
cardDisplay.clipsToBounds = YES;
cardDisplay1.layer.cornerRadius = 7;
cardDisplay1.clipsToBounds = YES;
[restartButton setHidden:YES];
}
- (IBAction)stop:(id)sender
{
stop1 = 86; //cancelled
[NSTimer scheduledTimerWithTimeInterval:2 target:self
selector:#selector(restartButtonDelay:) userInfo:nil repeats:NO];
}
-(void)restartButtonDelay:(NSTimer*)timer
{
[restartButton setHidden:NO];
}
-(void)cardDisplayDelay:(NSTimer*)timer
{
[cardDisplay setHidden:NO];
[cardDisplay1 setHidden:NO];
}
- (IBAction)hideShow:(id)sender
{
if ([cardCount isHidden])
{
[cardCount setHidden:NO];
[cardCount1 setHidden:NO];
[totalCount setHidden:NO];
}
else
{
[cardCount setHidden:YES];
[cardCount1 setHidden:YES];
[totalCount setHidden:YES];
}
}
- (IBAction)homeAction:(id)sender
{
stop1 = 86; //cancelled
}
#end
In the updating class .h
#protocol DoSomethingDelegate <NSObject>
-(void)doSomething;
#end
#property (assign, nonatomic) id <DoSomethingDelegate> delegate;
In the updating class .m
-(void)doSomethingSomewhereElse {
if (self.delegate != nil && [self.delegate respondsToSelector:#selector(doSomething)]) {
[self.delegate performSelector:#selector(doSomething)];
}
} else {
NSLog(#"Delgate doesn't implement doSomething");
}
}
In the receiving class' .h:
Conform to protocol <DoSomethingDelegate>
#interface myDoSomethingClass : NSObject <DoSomethingDelegate>
...
Implement the delegate method in the receiving class' .m:
-(void)someInit{
//set the delegate to self
}
In the view controller .m
-(void)doSomething{
NSLog(#"The delegate told me to do this!");
}
The deck is not its own delegate. Right now your code says that a Deck is a SpeedSliderDelegate, and that a Deck's delegate is a DeckLooperDelegate.
If you always need a delegate for Deck, you can do it this way:
- (id) initWithDelegate:(id<DeckLooperDelegate>)delegate {
if (self = [super init]) {
self.delegate = delegate;
cards = [[NSMutableArray alloc] init];
NSInteger aCount, picNum = 0;
// etc etc etc
}
}
Then, in the DeckLooperDelegate that creates the deck, you call it like this:
Deck *deck = [[Deck alloc] initWithDelegate:self];
Then you want your speed slider to set the deck as its delegate.
mySpeedSlider.delegate = deck;
Now mySpeedSlider can call [delegate setSpeed:] to change the deck's speed.

Calculator App - strange error: 'unrecognized selector sent to instance' when trying to update display

I'm relatively new to Objective-C, so I'm not 100% about everything I'm coding. However, I'm tackling my errors as they happen, and I am getting a run-time error that I'm not sure how to fix. The error claims that an 'unrecognized selector [was] sent to instance.'
- (IBAction) equalsPressed{
self.userIsInTheMiddleOfTypingANumber = NO;
if (self.brain.operationIsPicked) {
[self.brain pushOperand: [self.display.text doubleValue]];
double result = [self.brain performOperation: self.brain.operation];
// The line below this
self.display.text = [NSString stringWithFormat: #"%g", result];
}
}
I'm doing the Calculator app taught by the Stanford professor whose course is posted in iTunes U. However, I edited it to not include an enterPressed command and instead use an altered and more user-friendly 'equalsPressed.' After equalsPressed is finished (meaning when I click the equals sign on the calculator), the error is displayed. Might anyone know what is causing this problem? I already found someone else who has an error very similar to this one, but occurring in a slightly different place. Here are the other code snippets that could help elucidate the problem.
#import "CalculatorBrain.h"
#interface CalculatorBrain()
#property (nonatomic, strong) NSMutableArray *operandStack;
#end
#implementation CalculatorBrain
#synthesize operandStack = _operandStack;
#synthesize operandStackIsEmpty = _operandStackIsEmpty;
#synthesize operationIsPicked = _operationIsPicked;
#synthesize operation = _operation;
- (NSMutableArray *) operandStack {
if (!_operandStack) {
_operandStack =[[NSMutableArray alloc] init];
_operandStackIsEmpty = YES;
_operationIsPicked = NO;
}
return _operandStack;
}
- (void) resetStack {
[self.operandStack removeAllObjects];
self.operandStackIsEmpty = YES;
self.operationIsPicked = NO;
}
- (void) pushOperand : (double) operand{
[self.operandStack addObject: [NSNumber numberWithDouble:operand]];
self.operandStackIsEmpty = NO;
}
- (double) popOperand {
NSNumber *num = [self.operandStack lastObject];
if (num) {[self.operandStack removeLastObject];}
return [num doubleValue];
}
- (double) performOperation : (NSString *) operation{
double result = 0;
double num2 = [self popOperand];
double num1 = [self popOperand];
if ([operation isEqualToString:#"+"])
result = num2 + num1;
else if ([operation isEqualToString:#"-"])
result = num2 - num1;
else if ([operation isEqualToString:#"*"] || [operation isEqualToString:#"x"])
result = num2 * num1;
else if ([operation isEqualToString:#"/"]){
if (num2 == 0)
[self resetStack];
else
result = num2 / num1;
}
[self pushOperand:result];
self.operationIsPicked = NO;
return result;
}
#end
Also, the debugging NSLog that I had print the display in the console works correctly, BUT the display in the Calculator view doesn't actually update (when I used breakpoints to slow the function down).
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
#interface CalculatorViewController ()
#property (nonatomic) BOOL userIsInTheMiddleOfTypingANumber;
#property (nonatomic, strong) CalculatorBrain *brain;
#end
#implementation CalculatorViewController
#synthesize userIsInTheMiddleOfTypingANumber = _userIsInTheMiddleOfTypingANumber;
#synthesize brain = _brain;
#synthesize display = _display;
- (CalculatorBrain *) brain {
if (!_brain) {
_brain =[[CalculatorBrain alloc] init];
}
return _brain;
}
- (IBAction) digitPressed: (UIButton *)sender {
NSString *digit = [sender currentTitle];
if (self.userIsInTheMiddleOfTypingANumber)
self.display.text = [self.display.text stringByAppendingString: digit];
else {
self.display.text = digit;
self.userIsInTheMiddleOfTypingANumber = YES;
}
}
- (IBAction) clearPressed {
self.userIsInTheMiddleOfTypingANumber = NO;
self.display.text = #"0";
[self.brain resetStack];
}
- (IBAction) equalsPressed {
self.userIsInTheMiddleOfTypingANumber = NO;
if (self.brain.operationIsPicked) {
[self.brain pushOperand: [self.display.text doubleValue]];
double result = [self.brain performOperation: self.brain.operation];
self.display.text = [NSString stringWithFormat: #"%g", result];
NSLog(#"%#",self.display.text);
}
NSLog(#"%#",self.display.text);
}
- (IBAction) operationPressed:(UIButton *) sender {
if (self.userIsInTheMiddleOfTypingANumber) {
[self.brain pushOperand: [self.display.text doubleValue]];
self.brain.operation = [sender currentTitle];
self.brain.operationIsPicked = YES;
self.userIsInTheMiddleOfTypingANumber = NO;
NSLog(#"%#", sender.currentTitle);
}
}
Thank you!
To quote the answer in the comments:
"The full error said that I sent an invalid argument to "[self.brain equalsPressed:]". In reality, equalsPressed takes no argument, but when I was linking the '=' button in my view to its respective method, I forgot to indicate that the function took no arguments. Hence even though the function as I wrote it has no arguments, I told the compiler (to begin with) that it was supposed to take an argument."

iOS RPNCalculatorStanfordVidOne can't figure out why all but one line is working

I am 100% brand new to iOS.
I am watching Stanford U's videos online to learn iOS. I spent hours slowly going through the second video meticulously ensuring I didn't goof on a line of code. Everything was perfect until - Wouldn't ya know it - the LAST minute of coding.
My wife and I spent a good amount of time trying to figure it out but my code matches the professor's as best we can tell. Please help me. I am loving learning through these videos but I can't move on until I have this functioning and take time to review it.
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
#interface CalculatorViewController()
#property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber;
#property (nonatomic, strong) CalculatorBrain *brain;
#end
#implementation CalculatorViewController
#synthesize display = _display;
#synthesize userIsInTheMiddleOfEnteringANumber =
_userIsInTheMiddleOfEnteringANumber;
#synthesize brain = _brain;
- (CalculatorBrain *)brain
{
if (!_brain) _brain = [[CalculatorBrain alloc] init];
return _brain;
}
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = sender.currentTitle;
if (self.userIsInTheMiddleOfEnteringANumber)
{
self.display.text = [self.display.text stringByAppendingString:digit];
}
else
{
self.display.text = digit;
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
- (IBAction)enterPressed
{
[self.brain pushOperand:[self.display.text doubleValue]];
self.userIsInTheMiddleOfEnteringANumber = NO;
}
- (IBAction)operationPressed:(id)sender
{
if (self.userIsInTheMiddleOfEnteringANumber) [self enterPressed];
double result = [self.brain performOperation:sender.currentTitle]; // <- HERE IS THE LINE IN QUESTION
NSString *resultString = [NSString stringWithFormat:#"%g", result];
self.display.text = resultString;
}
#end
CalculatorBrain.m
#import "CalculatorBrain.h"
#interface CalculatorBrain()
#property (nonatomic, strong) NSMutableArray *operandStack;
#end
#implementation CalculatorBrain
#synthesize operandStack = _operandStack;
- (NSMutableArray *) operandStack
{
if (_operandStack == nil) _operandStack = [[NSMutableArray alloc] init];
return _operandStack;
}
- (void)pushOperand:(double)operand
{
[self.operandStack addObject:[NSNumber numberWithDouble:operand]];
}
- (double)popOperand
{
NSNumber *operandObject = [self.operandStack lastObject];
if (operandObject) [self.operandStack removeLastObject];
return [operandObject doubleValue];
}
- (double)performOperation:(NSString *)operation
{
double result = 0;
if ([operation isEqualToString:#"+"])
{
result = [self popOperand] + [self popOperand];
}
else if ([#"*" isEqualToString:operation])
{
result = [self popOperand] * [self popOperand];
}
[self pushOperand:result];
return result;
}
#end
I think the problem is with your if statement not closing properly.
- (IBAction)operationPressed:(id)sender
{
if (self.userIsInTheMiddleOfEnteringANumber){ [self enterPressed];
double result = [self.brain performOperation:sender.currentTitle];
NSString *resultString = [NSString stringWithFormat:#"%g", result];
self.display.text = resultString;
}
}
or
- (IBAction)operationPressed:(id)sender
{
if (self.userIsInTheMiddleOfEnteringANumber)
{
[self enterPressed];
}
double result = [self.brain performOperation:sender.currentTitle];
NSString *resultString = [NSString stringWithFormat:#"%g", result];
self.display.text = resultString;
}
Suggest looking at the pdf file of the tutorial for a more concrete code source. Hope that help.

I can not figure out how to resolve SIGABRT error in Xcode

I am working on a basic calculator app, following a tutorial for an iTunes U class. I thought I had worked it out perfectly but when I go to run the application in the simulator, I get an unexpected error. The calculator works by entering the number, pressing the enter button, entering the second number, then the enter button and then the operation. It allows me to append digits to form a multi-digit number, but as soon as I press "enter" it quits out and says "Thread 1: Program received signal: "SIGABRT."" I have double and triple checked my code and cannot seem to find anything wrong, so i thought i would post it all on here and see if you guys can figure it out. Thanks in advance!
CalculatorBrain.h
#import <Foundation/Foundation.h>
#interface CalculatorBrain : NSObject
- (void)pushOperand:(double)operand;
- (double)performOperation:(NSString *)operation;
#end
CalculatorBrain.m
#import "CalculatorBrain.h"
#interface CalculatorBrain()
#property (nonatomic, strong) NSMutableArray *operandStack;
#end
#implementation CalculatorBrain
#synthesize operandStack = _operandStack;
- (NSMutableArray *)operandStack
{
if (!_operandStack) {
_operandStack = [[NSMutableArray alloc] init];
}
return _operandStack;
}
- (void)pushOperand:(double)operand
{
NSNumber *operandObject = [NSNumber numberWithDouble:operand];
[self.operandStack addObject:operandObject];
}
- (double)popOperand
{
NSNumber *operandObject = [self.operandStack lastObject];
if (operandObject) [self.operandStack removeLastObject];
return [operandObject doubleValue];
}
- (double)performOperation:(NSString *)operation
{
double result = 0;
if ([operation isEqualToString:#"+"]){
result = [self popOperand] + [self popOperand];
} else if ([#"*" isEqualToString:operation]) {
result = [self popOperand] * [self popOperand];
} else if ([operation isEqualToString:#"-"]) {
double subtrahend = [self popOperand];
result = [self popOperand] - subtrahend;
} else if ([operation isEqualToString:#"/"]) {
double divisor = [self popOperand];
if (divisor) result = [self popOperand] / divisor;
}
[self pushOperand:result];
return result;
}
#end
CalculatorViewController.h
#import <UIKit/UIKit.h>
#interface CalculatorViewController : UIViewController
#property (weak, nonatomic) IBOutlet UILabel *display;
#end
CalculatorViewController.m
#import "CalculatorViewController.h"
#import "CalculatorBrain.h"
#interface CalculatorViewController()
#property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber;
#property (nonatomic, strong) CalculatorBrain *brain;
#end
#implementation CalculatorViewController
#synthesize display;
#synthesize userIsInTheMiddleOfEnteringANumber;
#synthesize brain = _brain;
- (CalculatorBrain *)brain
{
if(!_brain) _brain = [[CalculatorBrain alloc] init];
return _brain;
}
- (IBAction)digitPressed:(UIButton *)sender {
NSString *digit = [sender currentTitle];
if (self.userIsInTheMiddleOfEnteringANumber) {
self.display.text = [self.display.text stringByAppendingString:digit];
} else {
self.display.text = digit;
self.userIsInTheMiddleOfEnteringANumber = YES;
}
}
- (IBAction)enterPressed
{
[self.brain pushOperand:[self.display.text doubleValue]];
self.userIsInTheMiddleOfEnteringANumber = NO;
}
- (IBAction)operationPressed:(UIButton *)sender
{
if (self.userIsInTheMiddleOfEnteringANumber) {
[self enterPressed];
}
NSString *operation = [sender currentTitle];
double result = [self.brain performOperation:operation];
self.display.text = [NSString stringWithFormat:#"%g", result];
}
#end
Open CalculatorViewController.xib file in Xcode and right-click the "File's Owner".
Check the appearing pop-up if you have any linked properties listed that are not implemented in the CalculatorViewController.h file (according to the above posted code, the only properties linked from .xib to .h should be a UILabel called "display". Delete all invalid linked properties, if any is available (invalid linked properties would be marked with a yellow warning sign).
Expand your project Executable and right click on it. and click on GetInfo->Argument tag aat end of the window you see plus and minus sign button click on + sighn button and write
Name Value
NSZombieEnabled YES
then after execute your project and whenever crash your application click on run munu-> console you see there why your application crash. please try this may be this will help you.

Objective C Calculator Programming Variable

Okay, so I've been working on the Stanford iOS development course that they have posted for free online. I've been working on figuring out how to make a programable variable. It has been working fine so far, aside from the fact that I think the following lines of code are programming the variable to be #"x=" instead of the previous number entered.
The View Controller:
#import "ViewController.h"
#import "CalculatorBrain.h"
#interface ViewController()
#property (nonatomic) BOOL userIsInTheMiddleOfEnteringANumber;
#property (nonatomic) BOOL userPressedSomethingElse;
#property (nonatomic, strong) CalculatorBrain *brain;
#end
#implementation ViewController
#synthesize display;
#synthesize inputHistory;
#synthesize userPressedSomethingElse;
#synthesize userIsInTheMiddleOfEnteringANumber;
#synthesize brain = _brain;
- (CalculatorBrain *)brain
{
if (!_brain) _brain = [[CalculatorBrain alloc] init];
return _brain;
}
NSString *xValue = #"0";
- (IBAction)enterPressed
// A specific action if enter is pressed
{
[self.brain pushOperand:[self.display.text doubleValue]];
self.userIsInTheMiddleOfEnteringANumber = NO;
if (self.userPressedSomethingElse)
{
self.inputHistory.text = [self.inputHistory.text stringByAppendingString:#" "];
}
self.userPressedSomethingElse = NO;
}
- (IBAction)variableChanged:(id)sender
{
if (self.userIsInTheMiddleOfEnteringANumber)
{
[self enterPressed];
}
NSString *operation = [sender currentTitle];
xValue = [self.brain programVariable:operation];
self.inputHistory.text = [self.inputHistory.text stringByAppendingString:#"X="];
self.inputHistory.text = [self.inputHistory.text stringByAppendingString:xValue];
}
The Calculator Brain (the .m one):
#import "CalculatorBrain.h"
#interface CalculatorBrain()
#property (nonatomic,strong) NSMutableArray *operandStack;
#end
#implementation CalculatorBrain
#synthesize operandStack = _operandStack;
- (NSMutableArray *) operandStack
{
if (!_operandStack)
{
_operandStack = [[NSMutableArray alloc] init];
}
return _operandStack;
}
- (void) pushOperand:(double)operand
{
NSNumber *operandObject = [NSNumber numberWithDouble:operand];
[self.operandStack addObject:operandObject];
}
- (double)popOperand
{
NSNumber *operandObject = [self.operandStack lastObject];
if (operandObject) [self.operandStack removeLastObject];
return [operandObject doubleValue];
}
- (NSString *) programVariable: (NSString *) operation
{
double result = [self popOperand];
NSString *resultString = [NSString stringWithFormat:#"%.2d",result];
return resultString;
}
The .h Calculator Brain:
#import <Foundation/Foundation.h>
#interface CalculatorBrain : NSObject
- (void) pushOperand: (double) operand;
- (double) performOperation: (NSString *) operation;
- (NSString *) programVariable: (NSString *) operation;
#end
The button that is pushed says "x=", and because of some tracing statements I added, I have figured out that this is being set to xValue. However, I don't know how to fix it... Any ideas?
In your variableChanged:method, you possibly want if (!self.userIsInTheMiddleOfEnteringANumber) at the beginning. Note the logical negation, which I derive the need from the sense of your variable name. I see no way that variable is set, so I trust you are properly setting it elsewhere in your app.
Also, change the variable xValue to a instance variable on ViewController. It is currently a global static variable. If you have more than one ViewController objects created, you will have problems.