2
votes

Hey I'm trying to learn Objective-C and Cocoa Dev, but I'm having problems with making a Calculator App with a GUI. Here are my two files for my AppController class

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

Everything works fine except Add. For some reason The program crashes whenever I try to use Add. All the other functions work fine, but they are identical to each other. Why is this happening? Can someone please help me? I thank you in advance.

1

1 Answers

6
votes

You are using NSInteger* (pointer to NSInteger) to store variables that should simply be NSInteger. Try the following:

- (IBAction)add:(id)sender
{
    NSInteger value1 = [textField1 integerValue];
    ...
}