嘿我正在尝试学习Objective-C和Cocoa Dev,但是我在使用GUI制作计算器应用程序时遇到了问题。这是我的AppController类的两个文件
AppController.h
#import <Cocoa/Cocoa.h>
@interface AppController : NSObject
{
IBOutlet NSTextField *textField1;
IBOutlet NSTextField *textField2;
IBOutlet NSTextField *resultsField;
}
- (IBAction)add:(id)sender;
- (IBAction)multiply:(id)sender;
- (IBAction)subtract:(id)sender;
- (IBAction)divide:(id)sender;
@end
AppController.m
#import "AppController.h"
int addx(int x, int y)
{
return (x+y);
}
int subtractx(int x, int y)
{
return (x-y);
}
int multiplyx(int x, int y)
{
return (x*y);
}
int dividex(int x, int y)
{
return (x/y);
}
@implementation AppController
- (void) awakeFromNib
{
[textField1 setStringValue:@"Enter first value here"];
[textField2 setStringValue:@"Enter second value here"];
[resultsField setStringValue:@"Results come out here"];
}
- (IBAction)add:(id)sender
{
NSInteger *value1;
value1 = [textField1 integerValue];
NSInteger *value2;
value2 = [textField2 integerValue];
[resultsField setIntegerValue:addx(value1, value2)];
}
- (IBAction)subtract:(id)sender
{
NSInteger *value1;
value1 = [textField1 integerValue];
NSInteger *value2;
value2 = [textField2 integerValue];
[resultsField setIntegerValue:subtractx(value1, value2)];
}
- (IBAction)multiply:(id)sender
{
NSInteger *value1;
value1 = [textField1 integerValue];
NSInteger *value2;
value2 = [textField2 integerValue];
[resultsField setIntegerValue:multiplyx(value1, value2)];
}
-(IBAction)divide:(id)sender
{
NSInteger *value1;
value1 = [textField1 integerValue];
NSInteger *value2;
value2 = [textField2 integerValue];
[resultsField setIntegerValue:dividex(value1, value2)];
}
@end
除了Add之外,一切正常。出于某种原因,每当我尝试使用Add时,程序都会崩溃。所有其他功能都可以正常工作,但它们彼此完全相同。为什么会这样?有人可以帮帮我吗?我提前谢谢你。
答案 0 :(得分:6)
您正在使用NSInteger*
(指向NSInteger的指针)来存储应该只是NSInteger
的变量。请尝试以下方法:
- (IBAction)add:(id)sender
{
NSInteger value1 = [textField1 integerValue];
...
}