2014-12-05 47 views
-2

我是目標C的新程序員...我的代碼中有一些問題,我不知道爲什麼我得到一個錯誤... 這是我的代碼: Rectangle .H:getter and setter for int in objective c

#import <Foundation/Foundation.h> 



@interface Rectangle : NSObject 
    { 
     int width; 
     int height; 
    } 
     @property(setter=setWidthOfRect: , getter=getWidth) int width; 
     @property(setter=setHeightOfRect: , getter=getHeight) int height; 
@end 

Rectangle.m:

#import "Rectangle.h" 

@implementation Rectangle 
    @synthesize width, height; 
    @end 

,這是main.m文件:

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



int main(int argc, const char * argv[]) { 
    @autoreleasepool { 
     Rectangle *rect = [[Rectangle alloc] init]; 
     [rect setWidthOfRect:22]; 
     [rect setHeightOfRect:28]; 
    NSLog(@"the area is: %d", [rect getHeight] * [rect getWidth]); 

    } 
    return 0; 
} 

而我沒有得到這個:「該地區是616 任何幫助嗎?

+0

我做到了,它給出正確的答案。 – 2014-12-05 15:03:14

+0

我認爲你沒有看LOG或者它可能被關閉,意味着你正在看一些其他的東西,而不是控制檯。 – 2014-12-05 15:03:49

+0

它看起來沒問題,除了上面代碼中的一些複製粘貼,我正在編輯它。 – 2014-12-05 15:04:21

回答

2

這是更好地使用默認的getter/setter方法,只寫你的屬性是這樣的:

@property (nonatomic, assign) int width; 

你甚至都不需要編寫@synthesize和高德。比你可以這樣使用它:

object.width = 5; // or 
[object setWidth:5]; 

int width = object.width; // or 
int width = [object width]; 
+0

爲什麼你使用'nonatomic'?你關心表演嗎?或者你在這裏重寫setter或getter?除了你不需要使用'assign',因爲它是默認的非對象屬性,這意味着'@property int width;'綽綽有餘。 – Andy 2014-12-05 15:55:39

+0

只有當我知道這個代碼將從多個線程中使用時,我才使用'atomic'。在大多數情況下,事實並非如此。 'assign'怎麼樣,這只是我的代碼風格偏好。代碼在其他類型的屬性('weak','strong')附近看起來更加精確。而蘋果在他們的SDK頭文件中使用了相同的方法。 – ArtFeel 2014-12-08 11:33:18

+0

好吧,我假設一個品味的問題。 – Andy 2014-12-08 12:41:27

2

擺脫您的屬性寬度和高度以上的額外整數。一個屬性使得你已經指定了數據類型,並且在那裏你可以定義set屬性方法名是什麼,並且獲得屬性名稱以及其他屬性標誌。