我对objective-c完全不熟悉,所以我不知道为什么会这样。我仍然试图将我的大脑包围在概念中,我不知道我在寻找什么,所以我希望你们中的一个好,聪明的人可以帮助我。我确定这是一个愚蠢的事情,我没有意识到这是一个问题。
ViewController.h:
#import <UIKit/UIKit.h>
#import "CalculatorBrain.h"
@interface ViewController : UIViewController {
IBOutlet UILabel *display;
CalculatorBrain *brain;
BOOL userIsInTheMiddleOfTypingANumber;
}
- (IBAction)digitPressed:(UIButton *)sender;
- (IBAction)operationPressed:(UIButton *)sender;
@end
ViewController.m: (崩溃发生在“NSString * operation = [[sender titleLabel] text];”接近结尾)
#import "ViewController.h"
@interface ViewController ()
@end
@implementation ViewController
- (CalculatorBrain *)brain
{
if (brain) {
brain = [[CalculatorBrain alloc] init];
}
return brain;
}
- (IBAction)digitPressed:(UIButton *)sender
{
NSString *digit = [[sender titleLabel] text];
if (userIsInTheMiddleOfTypingANumber) {
[display setText:[[display text] stringByAppendingString:digit]];
} else {
[display setText:digit];
userIsInTheMiddleOfTypingANumber = YES;
}
}
- (IBAction)operationPressed:(UIButton *)sender
{
if (userIsInTheMiddleOfTypingANumber) {
[[self brain] setOperand:[[display text] doubleValue]];
userIsInTheMiddleOfTypingANumber = NO;
}
NSString *operation = [[sender titleLabel] text];
double result = [[self brain] performOperation:operation];
[display setText:[NSString stringWithFormat:@"%g", result]];
}
@end
CalculatorBrain.h:
#import <Foundation/Foundation.h>
@interface CalculatorBrain : NSObject {
double operand;
NSString *waitingOperation;
double waitingOperand;
}
- (void)setOperand:(double)anOperand;
- (double)performOperation:(NSString *)operation;
@end
CalculatorBrain.m:
#import "CalculatorBrain.h"
@implementation CalculatorBrain
- (void)setOperand:(double)anOperand
{
operand = anOperand;
}
- (void)performWaitingOperation
{
if ([@"+" isEqual:waitingOperation]) {
operand = waitingOperand + operand;
} else if ([@"-" isEqual:waitingOperation]) {
operand = waitingOperand - operand;
} else if ([@"*" isEqual:waitingOperation]) {
operand = waitingOperand * operand;
} else if ([@"/" isEqual:waitingOperation]) {
if (operand) {
operand = waitingOperand / operand;
}
}
}
- (double)performOperation:(NSString *)operation
{
if ([operation isEqual:@"sqrt"]) {
operand = sqrt(operand);
} else {
[self performWaitingOperation];
waitingOperation = operation;
waitingOperand = operand;
}
return operand;
}
@end
提前感谢任何帮助或提示......我不知道我在做什么:)
答案 0 :(得分:1)
- (CalculatorBrain *)brain {
if (brain) {
brain = [[CalculatorBrain alloc] init];
}
return brain;
}
虽然代码可能有其他问题,但这个问题立刻就出现了问题。你错过了!操作
- (CalculatorBrain *)brain {
if (!brain) {
brain = [[CalculatorBrain alloc] init];
}
return brain;
}
答案 1 :(得分:0)
您应该能够在XCode的调试控制台中找出崩溃的原因。
作为旁注,为什么不使用[sender currentTitle]
代替[[titleLabel] text]
?
答案 2 :(得分:0)
我知道这已经过时了,但我遇到的问题和这个问题完全相同,我发现我在同一行上偶然添加了一个断点。希望这可以帮助其他人解决这个问题。