[Solved] Assistance needed writing simple Objective-C program


There are of course many ways to set this up. I can remember being confused when starting out, below is an alternative example to give you something else to look at.

It is not intended to be fancy but just bare-bones so that you can see a minimal setup of the class with an initializer.

Note that the only value initialized is the const pi, of course, the radius can be initialized there as well, as nhgrif’s example shows quite nicely.

Hope this helps!

//  Circle.h

#import <Foundation/Foundation.h>

@interface Circle : NSObject
{
    double radius;
    double pi;
}

@property double radius, pi;

-(double) getArea;
-(double) getDiameter;
-(double) getCircumference;

@end

And then the implementation:

//  Circle.m

#import "Circle.h"

@implementation Circle

@synthesize radius, pi;

// Initialize with const pi:
- (id)init {
    self = [super init];
    if (self) {
        pi = 3.14159;
        NSLog(@"Circle created.");
    }
    return self;
}

-(double) getArea {
    return pi*radius*radius;
}

-(double) getDiameter {
    return 2*radius;
}

-(double) getCircumference {
    return 2*pi*radius;
}

@end

And then for main:

//  main.m

#import <Foundation/Foundation.h>
#import "Circle.h"

int main(int argc, const char * argv[])
{
    @autoreleasepool {

        Circle *aCircle = [[Circle alloc] init];

        // Use an arbitrary value:            
        [aCircle setRadius:2];

        NSLog(@"Area = %f",[aCircle getArea]);
        NSLog(@"Circumference = %f",[aCircle getCircumference]);
        NSLog(@"Diameter = %f",[aCircle getDiameter]);
        NSLog(@"Check pi = %f",[aCircle pi]);

    }
    return 0;
}

2

solved Assistance needed writing simple Objective-C program