且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

需要帮助编写简单的Objective-C程序

更新时间:2023-11-20 14:19:40

当然有很多方法可以设置。我可以记得在开始时感到困惑,下面是一个替代的例子,给你别的东西看看。

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.

请注意,初始化的唯一值是const pi,当然,半径也可以在那里初始化,正如nhgrif的例子很好地显示。

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.

希望这有助于!

//  Circle.h

#import <Foundation/Foundation.h>

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

@property double radius, pi;

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

@end

然后执行:

//  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

/ p>

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;
}