计算/变量返回为零

时间:2014-09-09 23:26:27

标签: objective-c instance-variables

我正在设置一个基本几何类,我在其中定义一个矩形,可以操纵宽度和高度,同时计算面积和周长。除了周长和区域变量返回零之外,一切正常并且输出正常。我不知道如何在@implementation内部正确设置变量,因此我确定它是从首次初始化变量时开始显示的零(在宽度和高度之前是设定)。

我对OOP和ObjC缺乏经验,所以我可能会遗漏一些简单的东西。

#import <Foundation/Foundation.h>

// @interface setup as required.
@interface Rectangle: NSObject
-(void) setWidth: (int) w;
-(void) setHeight: (int) h;
-(int) width;
-(int) height;
-(int) area;
-(int) perimeter;
-(void) print;
@end

// @implementation setup for the exercise.
@implementation Rectangle {
    int width;
    int height;
    int perimeter;
    int area;
}
// Set the width.
-(void) setWidth: (int) w {
    width = w;
}
// Set the height.
-(void) setHeight: (int) h {
    height = h;
}

// Calculate the perimeter.
-(int) perimeter {
    return (width + height) * 2;
}

// Calculate the area.
-(int) area {
    return (width * height);
}

-(void) print {
    NSLog(@"The width is now: %i.", width);
    NSLog(@"The height is now: %i.", height);
    NSLog(@"The perimeter is now: %i.", perimeter);
    NSLog(@"The area is now: %i.", area);
}
@end

int main(int argc, const char * argv[])
{
    @autoreleasepool {
        // Create an instance of Rectangle.
        Rectangle *theRectangle;
        theRectangle = [Rectangle alloc];
        theRectangle = [theRectangle init];
        // Use the designed methods.
        [theRectangle setWidth: 100];
        [theRectangle setHeight: 50];
        [theRectangle print];
    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

简答:

调用您的对象方法:

 [self perimeter];
 // as in
 NSLog(@"The perimeter is now: %i.", [self perimeter]);

而不仅仅是

 perimeter

访问具有该名称的变量,而不是调用您已定义的方法。

更长的回答:

您的代码中有几件事可以改进:

您应该使用属性而不是ivars和方法来获取和设置它们。声明如下的属性:@property (nonatomic) int width;将为您提供由编译器隐式创建的getter和setter。那么你可以做其中任何一个来设置一个值:

theRectangle.width = 100;
// is the same as:
[theRectangle setWidth:100];

您也可以覆盖您的getter和setter。您还可以创建只读属性,例如

@interface Rectangle: NSObject

@property (nonatomic) int width;
@property (nonatomic) int height;
@property (nonatomic, readonly) int perimeter;

@end

@implementation Rectangle

- (int)perimeter
{
    return self.width * self.height * 2;
}

@end