1

私はiOSを初めて使用し、メソッドを記述しているときにiOSのパターンに従うのに少し問題があります。私はobjective-cを使用して日付の値をインクリメントする簡単な方法を見つけようとしています。

考慮事項:

NSInteger incrementType = 1; // from 1 to 4, days, weeks, months, year
NSInteger incrementSize = 20 // the increment size
NSDate* date = ... // some date

    +(NSDate*)somename:(NSInteger)incrementSize type:(NSInteger)incrementType current:(NSDate*)date {

        NSCalendar* gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

        NSDateComponents* ateComponents = [[NSDateComponents alloc] init];
       // switch    
       [weekdayComponents setMonth:incrementSize];

        NSDate* newDate = [gregorian dateByAddingComponents:dateComponents toDate:date options:0];

        return newDate;

    }

問題:

  1. 論理が正しいかどうかはわかりません。stackoverflowでコードの一部を見つけ、それを変更しようとしています。
  2. 増分タイプパラメーターの列挙型を作成するにはどうすればよいですか?
  3. 良いメソッドシグネチャは何でしょうか?
4

1 に答える 1

4

以前も同じ課題があり、NSDate(ARCを使用して)単純なカテゴリを作成しました。

NSDate + Utils.h:

@interface NSDate (Utils)

-(NSDate *)addDays:(NSInteger)days weeks:(NSInteger)weeks months:(NSInteger)months years:(NSInteger)years;

@end

NSDate + Utils.m:

#import "NSDate+Utils.h"

@implementation NSDate (Utils)

-(NSDate *)addDays:(NSInteger)days weeks:(NSInteger)weeks months:(NSInteger)months years:(NSInteger)years {
    NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
    [offsetComponents setDay:days];
    [offsetComponents setWeek:weeks];
    [offsetComponents setMonth:months];
    [offsetComponents setYear:years];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    return [calendar dateByAddingComponents:offsetComponents toDate:self options:0];
}

@end

また、上記のメソッドをすべて呼び出すいくつかの単純なメソッドを作成しました(未使用のコンポーネントはゼロです)。それらの署名は次のとおりです。

-(NSDate *)addDays:(NSInteger)days;
-(NSDate *)addWeeks:(NSInteger)weeks;
-(NSDate *)addMonths:(NSInteger)months;
-(NSDate *)addYears:(NSInteger)years;

addDaysこのようなものです:

-(NSDate *)addDays:(NSInteger)days {
  return [self addDays:days weeks:0 months:0 years:0];
}

特に、これらのメソッドはincrementType列挙の必要性を取り除きます。

于 2012-10-22T01:48:38.430 に答える