2014-09-09 7 views
-2

저는 사각형을 정의하고 면적과 둘레를 계산하면서 너비와 높이를 조작 할 수있는 기본 지오메트리 클래스를 설정하고 있습니다. 경계선과 영역 변수가 0으로 돌아가는 것을 제외하면 모든 것이 올바르게 작동하고 출력됩니다. 변수 자체를 올바르게 설정하는 법이나 @implementation 중에 변수를 설정하는 방법을 모르므로 변수가 처음 초기화 될 때 (너비와 높이가 설정되기 전에) 0을 표시하고 있다고 확신합니다.계산/변수가 0으로 돌아 오는 변수

저는 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; 
} 
+0

재산 –

+0

당신이 오래된 자습서를 따르고 있습니다이를 확인 바르를 사용하지 않는? 이 클래스 선언은 현대 기능을 사용하지 않습니다. –

+0

예. 책에서 나는 그것을 들고 일반 연습을 사용했다. 머리를 가져 주셔서 감사합니다. 나는 책에서 낡은 것보다 당신이 말하는 것처럼 제대로 배우고 싶습니다. 체크 아웃 할만한 좋은 자료를 알고 있습니까? – user3223880

답변

0

짧은 답변 :이 같은

전화 개체 방법 : 대신 해당 이름을 가진 변수에 액세스

perimeter 

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

, 대신 정의한 메서드를 호출합니다.

긴 대답 : 향상시킬 수 코드에서 몇 가지가 있습니다

:

당신이 얻을 그들을 설정하는 속성 대신 인스턴스 변수와 메소드를 사용해야합니다. 다음과 같이 선언 된 속성 : @property (nonatomic) int width;은 컴파일러에서 암시 적으로 만든 getter 및 setter를 제공합니다. 그럼 당신은 값을 설정하려면 다음 중 하나를 수행 할 수 있습니다 : 당신은 너무 당신의 getter 및 setter는 재정의 할 수 있습니다

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

. 읽기 전용 속성을 만들 수도 있습니다 (예 :

@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 
+0

일부 연구 중에 @property를 보았고이를 적용하는 방법에 대해 생각했지만 이해하지 못했습니다. 신속하고 간결하고 명확한 대답에 감사드립니다. – user3223880

+0

@ user3223880 여러분을 환영합니다. 나는 방금 대답을 조금 확장했다. – Macondo2Seattle