Saturday, July 19, 2014

Objectiv-C examples and exercises

Some exercises and code example from an Objectiv-C programming book. Put here for future reference.

Date calculation 1:

# obj-c code

int main(int argc, const char * argv[])

    @autoreleasepool {

        // initialize a date with current date and time
//      NSDate *now = [NSDate date];
        NSDate *now = [[NSDate alloc] init];
        NSLog(@"now lives at %p", now);
        NSLog(@"now is %@", now);
        double seconds = [now timeIntervalSince1970];
        NSLog(@"It has been %f seconds since 1970", seconds);

        // add seconds to date
        NSDate *later = [now dateByAddingTimeInterval:100000];
        NSLog(@"later lives at %p", later);
        NSLog(@"later is %@", later);

        // initialize a date by components (year, month, day, ...)
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        [comps setYear:1994];
        [comps setMonth:9];
        [comps setDay:12];
        [comps setHour:0];
        [comps setMinute:0];
        [comps setSecond:0];
        NSLog(@"date of birth: %@", comps);

        // calendar object
        NSCalendar *g = [[NSCalendar alloc]  initWithCalendarIdentifier:NSGregorianCalendar ];
        // initialize date from components under a certain calendar
        NSDate *dob = [g dateFromComponents:comps];
        NSLog(@"date of birth: %@", dob);
        // calc interval between two dates
        double d = [now timeIntervalSinceDate:dob];
        NSLog(@"It has been %f seconds since you were born!", d);
    return 0;

int main(int argc, const char * argv[])

    @autoreleasepool {
        // get timezone and whether it's day light saving time
        NSTimeZone *myzone = [NSTimeZone systemTimeZone];
        BOOL isdls = [myzone isDaylightSavingTime];
        NSLog(@"Is it day light savings time in my zone? %s", isdls ? "Yes!" : "No!");

    return 0;