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
1 | NSDate *today = [ NSDate date]; |
4 | NSCalendar *calendar = [ NSCalendar currentCalendar]; |
6 | NSDateComponents *components = |
7 | [calendar components: NSCalendarUnitYear |
8 | | NSCalendarUnitMonth | NSCalendarUnitDay | |
9 | NSCalendarUnitWeekday | NSCalendarUnitHour | |
10 | NSCalendarUnitMinute | NSCalendarUnitSecond fromDate:today]; |
13 | NSInteger Wyear = components.year; |
14 | NSInteger Wmonth = components.month; |
15 | NSInteger Wday = components.day; |
17 | NSInteger Wweekday = components.weekday; |
20 | NSInteger Whour = components.hour; |
21 | NSInteger Wmin = components.minute; |
22 | NSInteger Wsec = components.second; |
25 | NSCalendar * calendar2 = [ NSCalendar currentCalendar]; |
26 | NSDateComponents * components2 = |
27 | [calendar2 components: NSCalendarUnitWeekOfYear fromDate:today]; |
28 | NSInteger Wthisweek = components2.weekOfYear; |
31 | NSCalendar *calendar3 = [ NSCalendar currentCalendar]; |
33 | NSDateFormatter *fmt = [[ NSDateFormatter alloc] init]; |
34 | [fmt setDateFormat: @"yyyyMMdd" ]; |
36 | NSString *date0101 = @"20180101" ; |
38 | NSDate *formatterdate0101 = [fmt dateFromString:date0101]; |
40 | NSDateComponents *components3 = |
41 | [calendar3 components: NSCalendarUnitYear |
42 | | NSCalendarUnitMonth | NSCalendarUnitDay |
43 | | NSCalendarUnitWeekday |
44 | fromDate:formatterdate0101]; |
46 | NSInteger weekday0101 = components3.weekday; |
49 | NSInteger Count_day = (Wthisweek - 1) * 7 |
50 | + Wweekday - (weekday0101 - 1) ; |
古典的なロジックでは、以下の方法が容易と思われます。ポイントは、caseにbreakを入れていない点です。上記の「今日は今年第何週目」以降の差し替えになります。
1 | NSInteger Count_day = 0; |
5 | Count_day = Count_day + 30; |
7 | Count_day = Count_day + 31; |
9 | Count_day = Count_day + 30; |
11 | Count_day = Count_day + 31; |
13 | Count_day = Count_day + 31; |
15 | Count_day = Count_day + 30; |
17 | Count_day = Count_day + 31; |
19 | Count_day = Count_day + 30; |
21 | Count_day = Count_day + 31; |
23 | Count_day = Count_day + 28; |
25 | if ((Wyear % 4) == 0){ |
27 | Count_day = Count_day + 1; |
31 | Count_day = Count_day + 31; |
34 | Count_day = Count_day + Wday; |