[英]value comes out as zero for rectangle class
當我編譯它時,我總是得到零而不是值的任何建議?
這里的代碼是關於我創建的一個簡單的矩形類。
#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]); } }
您翻轉了變量分配:
-(void) setWH:(int)h :(int)w {
w = width;
h = height;
}
它應該是
-(void) setWH:(int)h :(int)w {
width = w;
height = h;
}
一開始,我什至不了解它是如何編譯的,因為沒有self
無法訪問屬性。 然后我看到了實例變量。
@interface Rectangle : NSObject {
int width;
int height;
}
@property int width, height;
不要那樣做 在現代的objective-c中,您根本不必為屬性編寫實例變量,它們將自動合成(通過您也不需要@synthesize
方式)。 當然,您可以自由地編寫它們(尤其是如果您開始學習OBjective-C時),但是最好為實例變量選擇其他名稱,因為否則會引起混淆。 一種標准做法是在屬性名稱前添加下划線。
//interface
@property (nonatomic, assign) int myProperty;
//implementation
@synthesize myProperty = _myProperty; //this will synthesize a getter, a setter and an instance variable "_myProperty"
通常,您應該更喜歡訪問屬性而不是實例變量,因為這樣您就可以更改屬性(存儲數據的getters / setters /方法)實現,而無需更改其他任何東西。 因此,對於area
和perimeter
,更好的解決方案是這樣的(@PerfectPixel已經告訴您有關return
因此請注意self
)。
-(int) area {
return self.width * self.height;
}
-(int) perimeter {
return (self.width + self.height) * 2;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.