简体   繁体   中英

value comes out as zero for rectangle class

  1. When I compile this I keep getting zeros instead of the values any suggestions?

  2. The code here is about a simple rectangle class I created.

      #import <Foundation/Foundation.h> @interface Rectangle : NSObject { int width; int height; } @property int width, height; -(int) area; -(int) perimeter; -(void) setWH: (int) h: (int) w; @end #import "Rectangle.h" @implementation Rectangle @synthesize width, height; -(int) area { width*height; } -(int) perimeter { (width+height)*2; } -(void) setWH:(int)h :(int)w { w = width; h = height; } @end #import <Foundation/Foundation.h> #import "Rectangle.h" int main (int argc, const char*argv[]) { @autoreleasepool { Rectangle* r = [[Rectangle alloc]init]; [r setWH: 6:8]; NSLog(@"the width of the rectangle is %i and the hieght %i", r.width, r.height); NSLog(@"the area is %i and the perimeter is %i", [r perimeter], [r area]); } } 

you flipped the variable assignment:

-(void) setWH:(int)h :(int)w {
       w = width;
       h = height;
 }

it should be

-(void) setWH:(int)h :(int)w {
       width = w;
       height = h;
 }

In the beginning I didn't understand how it even compiles, since you can't access a property without self . Then I saw instance variables.

 @interface Rectangle : NSObject {
       int width;
       int height;
 }
 @property int width, height;

Don't do that. In modern objective-c you don't have to write instance variables for properties at all, they will be automatically synthesized (by the way you don't need @synthesize either). You are free to write them, of course (especially if you're starting to learn OBjective-C) but then you'd better pick other names for instance variables, because otherwise it causes confusion. A standard practice is to prepend a property name with an underscore.

//interface
@property (nonatomic, assign) int myProperty;

//implementation
@synthesize myProperty = _myProperty; //this will synthesize a getter, a setter and an instance variable "_myProperty"

And you should generally prefer to access properties instead of instance variables, because this way you'll be able to change properties (getters/setters/methods of storing data) implementation without changing everything else. So for area and perimeter a better solution would be like this (@PerfectPixel already told you about return so just note self ).

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM