Amazon.com Widgets Craig's Answer
Welcome, Guest. Please login or register.
Did you miss your activation email?
November 29, 2014, 02:37:57 AM
Home Help Search chat Login Register 
News: Read this please.The Great Kangaroo Escape Looking for reviews of the 4th ed on Amazon!   Twitter:  @skochan
                     

+ Official Forum for Programming in Objective-C (the iPhone Programming Language) - Stephen Kochan
|-+ Old Stuff
| |-+ Webcast Series Part I, Sept. 1 - 24
| | |-+ Chapter 4, Exercise 7
| | | |-+ Craig's Answer
Pages: [1] Go Down
Print
Author Topic: Craig's Answer (Read 995 times)
howcr
Newbie
*
Posts: 5






on: September 08, 2009, 11:21:20 AM

Hi,

Interface:
Code: (Objective-C)
#import <Cocoa/Cocoa.h>

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

-(void) setWidth: (int) w;
-(void) setHeight: (int) h;
-(int) width;
-(int) height;
-(int) area;
-(int) perimeter;

@end

Implementation:
Code: (Objective-C)
#import "Rectangle.h"

@implementation Rectangle

-(void) setWidth: (int) w
{
width = w;
}

-(void) setHeight: (int) h
{
height = h;
}

-(int) width
{
return width;
}

-(int) height
{
return height;
}

-(int) area
{
// A = H * W
return height * width;
}

-(int) perimeter
{
// P = 2(H) + 2(W)
int x = 2;
return (x * height) + (x * width);
}

@end

Test Program:
Code: (Objective-C)
#import <Foundation/Foundation.h>
#import "Rectangle.h"

int main (int argc, const char * argv[]) {
    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    //CH - create an instance of a Rectangle
   Rectangle *myRect = [[Rectangle alloc]init];

    //CH - set the rectangle height & width
    [myRect setHeight: 3];
    [myRect setWidth: 4];

    //CH - print out the results
    NSLog(@"Height: %i",[myRect height]);
    NSLog(@"Width: %i",[myRect width]);
    NSLog(@"Area: %i",[myRect area]);
    NSLog(@"Perimeter: %i",[myRect perimeter]);

    [myRect release];

    [pool drain];
    return 0;
}

Output:
Code: (Objective-C)
[Session started at 2009-09-08 14:13:10 -0400.]
2009-09-08 14:13:10.899 ch4_question7[45380:10b] Height: 3
2009-09-08 14:13:10.907 ch4_question7[45380:10b] Width: 4
2009-09-08 14:13:10.916 ch4_question7[45380:10b] Area: 12
2009-09-08 14:13:10.927 ch4_question7[45380:10b] Perimeter: 14

The Debugger has exited with status 0.

Regards,
Craig
Logged
skochan
Administrator
Hero Member
*****
Posts: 3114







Reply #1 on: September 16, 2009, 11:36:17 AM

Good job, Craig.   Now rewrite it to use the @property directive, synthesize your accessor methods, and use the dot operator.

Cheers,

Steve Kochan
Logged
Pages: [1] Go Up
Print
Jump to:



Login with username, password and session length

Powered by MySQL Powered by PHP Powered by SMF 1.1.11 | SMF © 2006-2009, Simple Machines LLC Valid XHTML 1.0! Valid CSS!
Entire forum contents (c) 2009 classroomM.com. All rights reserved.