You might be inclined to think that
Objective C programs are very similar to
C; programs, with perhaps a smattering of
bracket notation. I've found that the
Objective C dialect used in
MacOS X's
cocoa API isn't much like
classic C at all.
Here's a cocoa version.
main.m
#import "beer.h"
#import <Cocoa/Cocoa.h>
int main(int argc, const char *argv [ ])
{
NSAutoreleasePool *pool = [ [NSAutoreleasePool alloc ] init ];
beerSupply *wall= [ [beerSupply alloc ] initWithQuantity:99 ];
[wall doSong ];
[pool release ];
return 0;
}
beer.h
#import
@interface beer:NSObject{
}
@end
@interface beerSupply:NSObject {
NSMutableArray *beers;
}
-(id)initWithQuantity:(unsigned int)aNumber;
-(void) dealloc;
-(NSString*)descriptionWithWall:(BOOL)wall;
-(int)doVerse;
-(void)doSong;
-(NSString*)drinkBeer;
@end
beer.m
#import "beer.h"
@implementation beer
@end
@implementation beerSupply
-(id)initWithQuantity:(unsigned int)aNumber
{
unsigned i;
self = [super init ];
beers= [NSMutableArray arrayWithCapacity:aNumber ];
for(i=0;i < aNumber;++i)
{
[beers addObject: [ [ [beer alloc ] init ] autorelease ] ];
}
return self;
}
-(void)dealloc
{
[beers release ];
[super dealloc ];
}
-(NSString*)descriptionWithWall:(BOOL)wall
{
NSString *aString;
if( [beers count ]!=1){
aString = [NSString stringWithFormat:@"%i Bottles of Beer", [beers count ] ];
}
else{
aString = [NSString stringWithFormat:@"One Bottle of Beer", [beers count ] ];
}
if(wall)
if( [beers count ])
aString= [aString stringByAppendingString:@" on the wall." ];
else
aString= [aString stringByAppendingString:@". Go to the Store and Buy Some More" ];
return aString;
}
-(int)doVerse
{
NSLog( [self descriptionWithWall:NO ]);
NSLog( [self descriptionWithWall:YES ]);
NSLog( [self drinkBeer ]);
NSLog( [self descriptionWithWall:YES ]);
return [beers count ];
}
-(NSString*)drinkBeer
{
[beers removeLastObject ];
return [NSString stringWithString:@"Take One Down, Pass it Around" ];
}
-(void)doSong
{
do ; while( [self doVerse ]);
}
@end
Of course, the main advantage of of the
Cocoa API is that it allows a
programmer to create a GUI. I'm not sure what kind of
GUI might be appropriate for a
drinking song, however.