目录
一、传入单个参数和多个参数
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSDate* now = [NSDate date];
NSLog(@"This NSDate object lives at %p", now);
NSLog(@"The Date is %@", now);
double seconds = [now timeIntervalSince1970];
NSLog(@"It has been %f seconds since the start of 1970.", seconds);
//传入一个实参的方法
//计算当前时间的后100000秒是什么时间
NSDate* later = [now dateByAddingTimeInterval:100000];
NSLog(@"In 100000 seconds it will be %@", later);
//传入多个实参的方法
//计算某个日期对应月份中的第几日(几号)。要获取这类信息需要使用NSCalender对象
NSCalendar* cal = [NSCalendar currentCalendar];
//查看我当前的历法,默认使用高利历法(公历)
NSLog(@"My calendar is %@", [cal calendarIdentifier]);
//三个冒号代表要传入三个参数,通常以冒号对齐
unsigned long day = [cal ordinalityOfUnit:NSDayCalendarUnit
inUnit:NSMonthCalendarUnit
forDate:now];
NSLog(@"This is day %lu of the month", day);
}
return 0;
}
冒号是构成方法的一个重要组成部分,:后意味着要传入一个实参
如果要计算出某个日期是相应月份的第几周,需将第一个参数改为ordinalityOfUnit:NSWeekCalendarUnit即可。
二、消息的嵌套发送
double seconds = [[NSDate date] timeIntervalSince1970];
系统会NSDate类发送date消息,然后向得到的返回值(即指向新创建的NSDate实例的指针)发送timeIntervalSince1970消息
三、alloc 和 init
每个类都有alloc类方法。它能够创建一个新的对象,并返回指向该对象的指针。
通过alloc创建出来的对象,必须经过初始化才能使用。
如果创建出来的新对象没有经过初始化,它会存在于内存里,但是无法接收消息。
每个类也都有一个init实例方法,用来初始化实例。
创建并初始化NSDate对象如下所示:
NSDate* now = [[NSDate alloc] init];
四、向nil发送消息
nil是值为0的指针,多数面向对象的语言不允许向nil发送消息。所以在发送消息前,必须检查指针是否为nil。
在OC里允许向nil发送消息,只是什么事情也不会发生。
五、id
id类型的含义是:可以指向任意类型OC对象的指针,注意id已经隐含了星号的作用
id now = [[NSDate alloc] init];
六、练习
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
id now = [[NSDate alloc] init];
NSLog(@"This NSDate object lives at %p", now);
NSLog(@"The Date is %@", now);
NSDateComponents* comps = [[NSDateComponents alloc] init];
[comps setYear:2001];
[comps setMonth:2];
[comps setDay:14];
[comps setHour:5];
[comps setMinute:20];
[comps setSecond:10];
NSCalendar* g = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDate* dateOfBirth = [g dateFromComponents:comps];
double seconds = [now timeIntervalSinceDate:dateOfBirth];
NSLog(@"it has been %f seconds", seconds);
}
return 0;
}