Xcode 開発で、かつて作成したアプリのカレンダ―関連機能で「 iOS 8.0 では最初は廃止予定」のメッセージが発生したので最新環境に対応した調査を行いました。
エラーメッセージは、警告レベル?なのでこのままでも問題ないようですが…
![]()
ーーーエラーメッセージーー
‘NSWeekOfYearCalendarUnit’ is deprecated: first deprecated in iOS 8.0 – Use NSCalendarUnitWeekOfYear instead
ーーー日本語訳ーーー
‘NSWeekOfYearCalendarUnit ‘は廃止されました:iOS 8.0では最初は廃止予定 – 代わりにNSCalendarUnitWeekOfYearを使用
今日は、今年何日目かを取得する機能を Xcode で実装してみました。Objective-c仕様
ポイント
・算出に当たって、大の月・小の月の判断は面倒
・できるだけObjective-c関数で対応
手順
・今日は、何月何日何曜日かを取得
・元日は、何曜日かを取得
・先週までの日数を計算 + 今日は今週何日目 - 元日の曜日より1日マイナス
例 2018年7月1日の場合
・今日は、7月1日日曜日(1)を取得、今週は、第27週目
・元日は、月曜日(2)を取得
・(先週は、第何週)* 7日 + 今週日曜日から何日目 - 元日は、日曜日から何日目 - 元日分マイナス
(27 – 1) * 7 + 1 - (2 – 1) = 182
・古典的な方法では、経過日で算出するので1月~6月まで+1日分の計算
31 + 28 + 31 + 30 + 31 + 30 + 1 = 182
NSDate *today = [NSDate date];
// NSDateComponentsで年・月・日・曜日を取得する
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components =
[calendar components: NSCalendarUnitYear
| NSCalendarUnitMonth|NSCalendarUnitDay |
NSCalendarUnitWeekday | NSCalendarUnitHour|
NSCalendarUnitMinute|NSCalendarUnitSecond fromDate:today];
//今時点の 年 月 日 曜日 (時 分 秒)
NSInteger Wyear = components.year;
NSInteger Wmonth = components.month;
NSInteger Wday = components.day;
NSInteger Wweekday = components.weekday;
//1:日曜日 2:月曜日 3:火曜日 4:水曜日 5:木曜日 6:金曜日 7:土曜日
NSInteger Whour = components.hour;//今回の処理に無意味です。
NSInteger Wmin = components.minute;//今回の処理に無意味です。
NSInteger Wsec = components.second;//今回の処理に無意味です。
//今日は今年第何週目
NSCalendar* calendar2 = [NSCalendar currentCalendar];
NSDateComponents* components2 =
[calendar2 components:NSCalendarUnitWeekOfYear fromDate:today];
NSInteger Wthisweek = components2.weekOfYear;
//今年の開始(元日)は何曜日
NSCalendar *calendar3 = [NSCalendar currentCalendar];
NSDateFormatter *fmt = [[NSDateFormatter alloc] init];
[fmt setDateFormat:@"yyyyMMdd"];
NSString *date0101 = @"20180101";//2018年固定の場合
NSDate *formatterdate0101 = [fmt dateFromString:date0101];
NSDateComponents *components3 =
[calendar3 components: NSCalendarUnitYear
| NSCalendarUnitMonth| NSCalendarUnitDay
| NSCalendarUnitWeekday
fromDate:formatterdate0101];
NSInteger weekday0101 = components3.weekday;//元日の曜日取得
//先週までの日数 + 今週日曜からの日数分 - 元日週の元日までの日数
NSInteger Count_day = (Wthisweek - 1) * 7
+ Wweekday - (weekday0101 - 1) ;
//先週まで × 7日 + 今週分 - 今年の0101日は、週のいつに始まったか
古典的なロジックでは、以下の方法が容易と思われます。ポイントは、caseにbreakを入れていない点です。上記の「今日は今年第何週目」以降の差し替えになります。
NSInteger Count_day = 0;
switch (Wmonth - 1) { //前月までの加算
case 11:
Count_day = Count_day + 30;
case 10:
Count_day = Count_day + 31;
case 9:
Count_day = Count_day + 30;
case 8:
Count_day = Count_day + 31;
case 7:
Count_day = Count_day + 31;
case 6:
Count_day = Count_day + 30;
case 5:
Count_day = Count_day + 31;
case 4:
Count_day = Count_day + 30;
case 3:
Count_day = Count_day + 31;
case 2:
Count_day = Count_day + 28;
if ((Wyear % 4) == 0){
Count_day = Count_day + 1;
}
case 1:
Count_day = Count_day + 31;
case 0:
Count_day = Count_day + Wday;//当月の日数
default:
break;
}
