2012-10-22 80 views
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. 如何爲incrementType參數編寫枚舉?
  3. 什麼是一個好的方法簽名?

回答

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枚舉的需要。

+0

我該如何使用它? 'NSDate * date = [NSDate date]; NSDate * newDate = [日期addDays:5];'? – lolol

+1

@lolol:是的,這就是要走的路! –