CS 489.02 - Computers and Games - Spring 2009
Objective-C


Loyola College > Department of Computer Science > Dr. James Glenn > CS 489.02 > Examples and Lecture Notes > Objective-C

point.h

#import <Foundation/Foundation.h>

@interface Point : NSObject
{
@private
  double x;
  double y;
}

-(id) initWithX:(double)initX andY:(double)initY;
-(id) initWithAngle:(double)theta andRadius:(double)r;
-(double) getX;
-(double) getY;
@end

point.m

#import <math.h>

#import "point.h"

@implementation Point

-(id) initWithX:(double)initX andY:(double)initY
{
  [super init];

  x = initX;
  y = initY;

  return self;
}

-(id) initWithAngle:(double)theta andRadius:(double)r
{
  [super init];

  x = r * cos(theta);
  y = r * sin(theta);

  return self;
}

-(double) getX
{
  return x;
}

-(double) getY
{
  return y;
}
@end

polygon.h

#import <Foundation/Foundation.h>
#import <Foundation/NSArray.h>

#import "point.h"

@interface Polygon : NSObject
{
  NSMutableArray* points;
}

-(id) init;
-(void) addPoint:(Point*) p;
-(Point*) getPoint:(int) i;
-(void) dealloc;
@end

polygon.m

#import <stdio.h>

#import "polygon.h"

@implementation Polygon
-(id) init
{
  [super init];

  points = [[NSMutableArray alloc] init];

  return self;
}

-(void) addPoint:(Point*) p
{
  // the array will retain p on its own, but for this example
  // I wanted it to be explicit that the Polygon retains the points

  [p retain];
  [points addObject:p];
}

-(Point*) getPoint:(int) i
{
  return [points objectAtIndex:i];
}

-(void) dealloc
{
  // see note about retained points above

  printf("Polygon.dealloc\n"); // apologies for the Java notation here

  for (int i = 0; i < [points count]; i++)
    {
      [[points objectAtIndex:i] release];
    }

  [points release];
  [super dealloc];
}
@end

GNUmakefile

# a pointer to the GNUstep makefiles on our machines
GNUSTEP_MAKEFILES = /usr/share/GNUstep/Makefiles

# I like C99...
ADDITIONAL_OBJCFLAGS = "-std=c99"

include $(GNUSTEP_MAKEFILES)/common.make

TOOL_NAME = Polygon
Polygon_OBJC_FILES = point.m polygon.m main.m

include $(GNUSTEP_MAKEFILES)/tool.make
This code can also be downloaded from the files
point.h, point.m, polygon.h, polygon.m, and GNUmakefile.