第一个objective-c程序,新建command line工程TimeAfterTime
创建并使用对象
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSDate *now = [NSDate date];
NSLog(@"The new date lives at %p", now);
}
return 0;
}
- 调用NSDate的data方法,创建一个NSDate的实例并以当前时间对其进行初始化
- 调用NSLog输出格式化字符串,用于格式化的字符串必须以@作为前缀
2015-01-28 20:26:19.222 TimeAfterTime[1280:15914] The new date lives at 0x100304e10
%p输出对象的地址,%@输出对象的描述信息<span style="white-space:pre"> </span>NSLog(@"The date is %@", now);
2015-01-28 20:36:50.213 TimeAfterTime[1789:20750] The date is 2015-01-28 12:36:50 +0000
函数调用
函数调用必须写在一对方括号中,在括号中写入指针和方法名,还可以给方法传递参数。
double seconds = [now timeIntervalSince1970];
NSLog(@"It has been %f seconds since the start of 1970.", seconds);
2015-01-28 20:41:39.781 TimeAfterTime[2037:23426] It has been 1422448899.777093 seconds since the start of 1970.
接下来创建另一个NSDate对象,其日期比之前得到的对象延后100000秒。 NSDate *later = [now dateByAddingTimeInterval:100000];
NSLog(@"In 100,000 seconds it will be %@", later);
2015-01-28 20:44:34.975 TimeAfterTime[2189:25143] In 100,000 seconds it will be 2015-01-29 16:31:14 +0000
当声明指针时,若知道对象类型,则声明如下:
NSDate *date;
若不确定对象类型,可以使用id类型,id类型类似于void*类型,星号为隐含。
id date
通过两个NSDate计算某人生日距今的秒数
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setYear:1969];
[comps setMonth:4];
[comps setDay:30];
[comps setHour:13];
[comps setMinute:10];
[comps setSecond:0];
NSCalendar *g = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
NSDate *dateOfBirth = [g dateFromComponents:comps];
double d = [now timeIntervalSinceDate:dateOfBirth];
NSLog(@"Seconds between birth date and now is %f", d);
程序执行结果如下:2015-01-28 20:53:39.880 TimeAfterTime[2655:29714] Seconds between birth date and now is 1443685419.876554
消息的嵌套发送
类方法alloc能够创建一个新的对象并返回指向该对象的指针,通过alloc创建的对象必须经过init才能被使用。
[[NSDate alloc] init];
系统先执行最里面的消息,alloc创建一个NSDate对象,再调用该对象的init方法。NSDate *now = [[NSDate alloc] init];
多个实参
使用NSCalender的ordinalityOfUnit:inUnit:forDate方法计算某天是该月中的第几日:
NSCalendar *cal = [NSCalendar currentCalendar];
NSUInteger day = [cal ordinalityOfUnit:NSCalendarUnitDay
inUnit:NSCalendarUnitMonth
forDate:now];
NSLog(@"This is day %lu of the month", day);
2015-01-28 21:11:52.485 TimeAfterTime[3559:39979] This is day 28 of the month
这个方法接收三个参数,用三个冒号分隔开。向nil发送消息
Objective-C支持向空指针发送消息,什么也不会发生
Dog *fido = nil;
Newspaper *daily = [fido goGetTheNewspaper];
像nil发送消息的返回值没有意义,此处为0。