// Times.m Copyright (c) Kari Laitinen // http://www.naturalprogramming.com // 2013-07-16 Objective-C version of this file was created. // 2013-07-16 Last modification. // Ohjelma toimii mutta .... // PitŠŠ selvittŠŠ miten tehdŠŠn virtuaalifunktioita OC:sssŠ. #include #import #include @interface CurrentTime : NSObject { int current_hours ; int current_minutes ; int current_seconds ; } - (id) init ; - (void) print ; @end @implementation CurrentTime - (id) init { self = [ super init ] ; if ( self ) { // Function time gives us seconds that have elapsed // since 1.1.1970 00:00:00. Function localtime converts // these seconds to more meaningful time units. time_t seconds_since_1970 ; time( &seconds_since_1970 ) ; current_hours = localtime( &seconds_since_1970 ) -> tm_hour ; current_minutes = localtime( &seconds_since_1970 ) -> tm_min ; current_seconds = localtime( &seconds_since_1970 ) -> tm_sec ; } return self ; } - (void) print { } @end // It is not entirely true that the 12-hour a.m./p.m. time // would be used everywhere in America, and the 24-hour time // would be used everywhere in Europe. The names AmericanTime // and EuropeanTime just happen to be nice names to // distinguish these two different ways to display time. @interface AmericanTime : CurrentTime - (void) print ; @end @implementation AmericanTime - (void) print { int american_hours[] = { 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 } ; printf( "%d:%02d:%02d", american_hours[ current_hours ], current_minutes, current_seconds ) ; if ( current_hours < 12 ) { printf( " a.m." ) ; } else { printf( " p.m." ) ; } } @end @interface EuropeanTime : CurrentTime - (void) print ; @end @implementation EuropeanTime - (void) print { printf( "%d:%02d:%02d", current_hours, current_minutes, current_seconds ) ; } @end int main( void ) { NSAutoreleasePool* autorelease_pool = [ [ NSAutoreleasePool alloc ] init ] ; CurrentTime* time_to_show ; printf( "\n Type 12 to see the time in 12-hour a.m./p.m format." "\n Any other number gives the 24-hour format. " ) ; int user_response ; scanf( "%d", &user_response ) ; if ( user_response == 12 ) { time_to_show = [ [ AmericanTime alloc ] init ] ; } else { time_to_show = [ [ EuropeanTime alloc ] init ] ; } printf( "\n The time is now " ) ; [ time_to_show print ] ; printf( "\n\n" ) ; [ autorelease_pool drain ] ; }