lolol
lolol

Reputation: 4390

Manipulating dates

I'm new to iOS and I'm getting a little trouble to follow the iOS patterns while writing a method. I'm trying to find a easy way to increment values in a date using objective-c.

Considering:

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;

    }

Problems:

  1. I'm not sure if the logic is correct. I found a piece of code in stackoverflow and I'm trying to modify it.
  2. How to write a enum for the incrementType parameter?
  3. What would be a good method signature?.

Upvotes: 1

Views: 268

Answers (1)

Jordão
Jordão

Reputation: 56497

I had the same challenge before, and I created a simple NSDate category (using 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

I also created a number of simple methods that all call the method above (with zeros on the unused components). Their signatures are:

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

addDays is like this:

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

In particular, these methods obviate the need for your incrementType enumeration.

Upvotes: 4

Related Questions