NSTimer、NSDate

###iOS时间那点事
经典看前必先看:iOS时间那点事NSCalendar + NSDateComponents
iOS 时区日期处理及定时 (NSDate,NSCalendar,NSTimer,NSTimeZone)

NSTimer

NSTimer 定时器用法总结

自动加一秒(dateByAddingComponents和dateByAddingTimeInterval)

参考:时间与日期处理
涉及知识点:
NSDate的生成
方法①通过NSDateFormatterdateFromString:方法对dateString生成NSDate;

1
2
3
4
5
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString *dateString = @"2016-08-15 22:55:03";
NSDate *date = [dateFormatter dateFromString:dateString];

方法②通过NSCalendardateFromComponents:方法对dateComponents生成NSDate;(dateComponents由分个字段生成)
[greCalendar dateFromComponents:dateComponents];

1
2
3
4
5
6
7
    NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:2016];
[dateComponents setMonth:8];
[dateComponents setDay:15];
NSDate *operationDate = [greCalendar dateFromComponents:dateComponents];

NSDate转NSString

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
NSDate *operationDate;

- (void)updateTimeExample {
NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *dateComponents = [[NSDateComponents alloc] init];
[dateComponents setYear:2016];
[dateComponents setMonth:8];
[dateComponents setDay:15];
operationDate = [greCalendar dateFromComponents:dateComponents];

if (!self.timer) {
self.timer = [NSTimer scheduledTimerWithTimeInterval:1.0 target: self selector:@selector(addOneSecondToDate:) userInfo:nil repeats:YES];
}
}

- (void)addOneSecondToDate:(NSTimer *)timer {
// NSDate *operationDate = [timer userInfo];
NSCalendar *greCalendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *offsetDateComponents = [[NSDateComponents alloc] init];
[offsetDateComponents setMinute:1];
[offsetDateComponents setSecond:1];
NSDate *finalDate = [greCalendar dateByAddingComponents:offsetDateComponents toDate:operationDate options:0];
operationDate = finalDate;

//NSDate转NSString
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy年MM月dd HH:mm:ss"];
NSString *dateString = [dateFormatter stringFromDate:finalDate];

self.networkTimeLabel.text = dateString;
}

#####NSJSONSerialization 去除不必要的空格回车
NSJSONSerialization介绍
NSJSONSerialization四个枚举什么意思

1
2
3
4
5
6
// 要去除不必要的空格回车,只需将参数Option设置为0即可。如果设置NSJSONWritingPrettyPrinted会使格式化的json更加可读,即添加空格和换行,但如果设为0,则不添加空格和换行
NSData *data = [NSJSONSerialization dataWithJSONObject:dictionary
options:0
error:nil];
NSString *JSON = [[NSString alloc] initWithData:data
encoding:NSUTF8StringEncoding];

######颜色渐变 CAGradientLayer
CAGradientLayer简介