// Animals.m Copyright (c) Kari Laitinen // http://www.naturalprogramming.com // 2013-06-09 File created. // 2013-06-09 Last modification. /* This program demonstrates: - a simple Objective-C class - having a 'copy constructor' in a class - using NSString objects and converting them to C-style strings - using the 'automatic memory management' of Objective-C */ #include #import @interface Animal : NSObject { NSString* species_name ; NSString* stomach_contents ; } - (id) init: (NSString*) given_species_name ; - (id) init_with_animal: (Animal*) another_animal ; - (NSString*) species_name ; // These two getters are needed by - (NSString*) stomach_contents ; // the 'copy constructor' - (void) feed: (NSString*) food_for_this_animal ; - (void) make_speak ; @end @implementation Animal - (id) init: (NSString*) given_species_name { self = [ super init ] ; if ( self ) { species_name = [ [ NSString alloc ] initWithString: given_species_name ] ; stomach_contents = [ [ NSString alloc ] initWithString: @"" ] ; } return self ; } - (id) init_with_animal: (Animal*) another_animal { self = [ super init ] ; if ( self ) { species_name = [ another_animal species_name ] ; stomach_contents = [ another_animal stomach_contents ] ; } return self ; } - (NSString*) species_name { return species_name ; } - (NSString*) stomach_contents { return stomach_contents ; } - (void) feed: (NSString*) food_for_this_animal { // A new NSString object is created by this method. // I suppose the memory for the old object is freed automatically. stomach_contents = [ NSString stringWithFormat: @"%@ %@,", stomach_contents, food_for_this_animal ] ; } - (void) make_speak { NSString* text_to_print = [ NSString stringWithFormat: @"\n Hello, I am a %@. \n I have eaten %@ \n", species_name, stomach_contents ] ; // The following statement converts a NSString to a // C-style string. According to documentation, the memory // of the C-style string will be automatically freed. printf( "%s", [ text_to_print UTF8String ] ) ; } @end int main( void ) { NSAutoreleasePool* autorelease_pool = [ [ NSAutoreleasePool alloc ] init ] ; Animal* cat_object = [ [ Animal alloc ] init: @"cat" ] ; Animal* dog_object = [ [ Animal alloc ] init: @"vegetarian dog" ] ; [ cat_object feed: @"fish" ] ; [ cat_object feed: @"chicken" ] ; [ dog_object feed: @"salad" ] ; [ dog_object feed: @"potatoes" ] ; Animal* another_cat = [ [ Animal alloc ] init_with_animal: cat_object ] ; [ another_cat feed: @"milk" ] ; [ cat_object make_speak ] ; [ dog_object make_speak ] ; [ another_cat make_speak ] ; [ autorelease_pool drain ] ; } /* NOTES: Useful links: http://stackoverflow.com/questions/2216266/printing-an-nsstring http://mobile.tutsplus.com/tutorials/iphone/learn-objective-c-day-5/ It seems that when the autorelease pool is in use, it is not good to try to release objects programmatically. This program can be compiled and run with commands such as: gcc Animals.m -o a.out -framework Foundation ./a.out */