1、oc中各种nil。
- nil
- 用来表示空对象,数组、字典结束判断
- Nil
- 用于类的空指针
- NSNull
- 用来标识什么都没有 [NSNull null],通常用于集合占位
- NULL
- 通用用于c指针变量为空
NSLog输出nil、Nil为(null),输出NSNull为<null>
- 通用用于c指针变量为空
2、判断两个日期是否在同一周
// 方法一
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
NSString *todayString = @"2019-10-07 03:02:00";
NSString *afterString = @"2019-10-06 00:08:33";
// 方法一
NSDate *today = [formatter dateFromString:todayString];
NSDate *afterDay = [formatter dateFromString:afterString];
formatter.dateFormat = @"yyyy-MM-dd HH:mm:ss E";
NSLog(@"今天: %@", [formatter stringFromDate:today]);
NSLog(@"之前: %@", [formatter stringFromDate:afterDay]);
NSInteger weekday = [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:today] weekday];
NSInteger afterweekday = [[[NSCalendar currentCalendar] components:NSCalendarUnitWeekday fromDate:afterDay] weekday];
weekday = weekday == 1 ? 7 : weekday - 1;
afterweekday = afterweekday == 1 ? 7 : afterweekday - 1;
NSLog(@"今天周 : %ld, 之前是: %ld",(long)weekday, afterweekday);
NSInteger startDay=[NSCalendar.currentCalendar ordinalityOfUnit:NSCalendarUnitDay inUnit: NSCalendarUnitYear forDate:afterDay];
NSInteger endDay=[NSCalendar.currentCalendar ordinalityOfUnit:NSCalendarUnitDay inUnit: NSCalendarUnitYear forDate:today];
NSLog(@"startDay : %ld, endDay: %ld ", (long)startDay, (long)endDay);
NSInteger distance = endDay - startDay;
NSLog(@"test : today: %@, afterDay: %@ %ld", today, afterDay, (long)distance);
if (labs(distance) > 6) {
NSLog(@"不在同一周");
} else if (distance > 0) {
if (distance < weekday) {
NSLog(@"在同一周");
} else {
NSLog(@"不在同一周");
}
} else {
if (labs(distance) <= 7 - weekday) {
NSLog(@"在同一周");
} else {
NSLog(@"不在同一周");
}
}
// 方法二(推荐使用)
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
calendar.firstWeekday = 2; // 周一是一周的开始第一天
NSCalendarUnit units = NSCalendarUnitWeekday | NSCalendarUnitYear | NSCalendarUnitWeekOfYear;
NSDateComponents *todayComp = [calendar components:units fromDate:today];
NSDateComponents *afterComp = [calendar components:units fromDate:afterDay];
NSLog(@"%@, \n %@ \n %@", todayComp, afterComp);
if (todayComp.year == afterComp.year && todayComp.weekOfYear == afterComp.weekOfYear) {
NSLog(@"在同一周");
} else{
NSLog(@"不在同一周");
}
3、Objective-C 中 nullable、__nullable、_Nullable 的区别
- 最开始使用的是__nullable,但是由于可能与第三方库冲突,苹果引进勒_Nullable,而且苹果支持不带下划线写法nullable
- (nullable NSString *)method;
- (NSString * __nullable)method;
- (NSString * _Nullable)method;
- 对于 双指针类型对象 、Block 的返回值、Block 的参数 等,这时候就不能用 nonnull/nullable 修饰,只能用带下划线的 __nonnull/__nullable 或者 _Nonnull/_Nullable:
- 苹果建议,对于属性、方法返回值、方法参数的修饰,使用:nonnull/nullable;
对于 C 函数的参数、Block 的参数、Block 返回值的修饰,使用:_Nonnull/_Nullable,建议弃用 __nonnull/__nullable。