Xcode (objective-c)で共通ロジックがあった場合、クラスメソッドを定義して使用することができます。
objective-cのクラスメソッドの使い方をまとめました。
サンプルプログラム
メインのプログラムで、日付から曜日を取得するロジックで、曜日取得だけをクラスメソッドにしたものです。
メインプログラム
2 | MyClass01 *myClass = [MyClass01 ClassMethod01]; |
4 | NSString *Wdate = @"20180411" ; |
5 | Wweekday = [myClass yasumi_chk1:Wdate]; |
6 | NSLog ( @"day,%ld" ,Wweekday); |
クラスメソッド(hファイル)
1 | @interface MyClass01 : NSObject |
5 | - ( NSInteger ) yasumi_chk1:( NSString *)date_set; |
クラスメソッド(mファイル)
3 | return [[ self alloc] init]; |
6 | - ( NSInteger ) yasumi_chk1:( NSString *)date_set{ |
9 | NSCalendar *calendar = [ NSCalendar currentCalendar]; |
11 | NSDateFormatter * dateFormatter = [[ NSDateFormatter alloc] init]; |
12 | [dateFormatter setDateFormat: @"yyyyMMdd" ]; |
15 | NSDate *chk_date = [dateFormatter dateFromString:date_set]; |
18 | NSDateComponents *comps = [calendar components: NSCalendarUnitWeekday fromDate:chk_date]; |
19 | NSInteger weekday = comps.weekday; |
「これってすごい」「みんなに教えたい!」と思ったらぜひ共有してみてください