gpt4 book ai didi

objective-c - 处理日期

转载 作者:行者123 更新时间:2023-12-01 18:26:45 25 4
gpt4 key购买 nike

我是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;

}

问题:
  • 我不确定逻辑是否正确。我在stackoverflow中找到了一段代码,我正在尝试对其进行修改。
  • 如何为incrementType参数编写枚举?
  • 什么是好的方法签名?
  • 最佳答案

    我之前遇到过同样的挑战,并且创建了一个简单的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枚举的需要。

    关于objective-c - 处理日期,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13003897/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com