《Objective-C编程(第2版)》13、14、17章练习题

《Objective-C编程(第2版)》学习笔记。

13章练习题

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSHost *host = [NSHost currentHost];
        NSString *comName = [host localizedName];
        NSLog(@"My computer name is %@", comName);
    }
    return 0;
}

14章练习题

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSDateComponents *comps = [[NSDateComponents alloc] init];
        [comps setYear:2015];
        [comps setMonth:12];
        [comps setDay:25];
        [comps setHour:13];
        [comps setMinute:10];
        [comps setSecond:20];

        // OS X 10.10 和 iOS 8之后不再使用NSGregorianCalendar,而是用NSCalendarIdentifierGregorian代替
        NSCalendar *cal = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
        NSDate *earliy = [cal dateFromComponents:comps];
        NSDate *now = [[NSDate alloc] init];

        double sec = [now timeIntervalSinceDate:earliy];

        // 默认输出的是零时区(格林尼治)时间
        NSLog(@"Seconds between %@ and %@ is %g", earliy, now, sec);
    }
    return 0;
}

17章练习题

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    @autoreleasepool {
        NSString *nameString = [NSString stringWithContentsOfFile:@"/usr/share/dict/propernames" encoding:NSUTF8StringEncoding error:NULL];
        NSString *wordString = [NSString stringWithContentsOfFile:@"/usr/share/dict/words" encoding:NSUTF8StringEncoding error:NULL];

        NSArray *names = [nameString componentsSeparatedByString:@"\n"];
        NSArray *words = [wordString componentsSeparatedByString:@"\n"];

        for (NSString *name in names) {
            for (NSString *word in words) {
                NSComparisonResult res = [name caseInsensitiveCompare:word];
                if (res == NSOrderedSame) {
                    NSComparisonResult r = [name compare:word];
                    if (r == NSOrderedAscending) {
                        NSLog(@"%@", word);
                    }
                }
            }
        }
    }
    return 0;
}


CashQian Blog

欢迎来到我的个人博客网站

友情链接

Powered by Python Blog. Copyright © 2016.

www.cashqian.net. All rights reserved.