开发者

NSDateComponents wrapped in a struct?

开发者 https://www.devze.com 2023-03-21 05:24 出处:网络
I am using NSDateComponents a lot in my app. The code is long and I have to do a lot of copy & past开发者_如何学Pythoning and when that happens in programming it\'s a sign that something can be do

I am using NSDateComponents a lot in my app. The code is long and I have to do a lot of copy & past开发者_如何学Pythoning and when that happens in programming it's a sign that something can be done better :). I read the ticked answer for that question and got all excited:

NSDate get year/month/day

(Read the comments) How can I wrap them on a struct? Sorry if that's a really beginners question but well... I'm a beginner. Or is there any other way to deal with that? Thanks!


You can declare your structure like this:

struct DateParts
{
    NSInteger day;
    NSInteger month;
    NSInteger year;
};

Then assign the parts:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
DateParts theParts;
theParts.day = [components day];    
theParts.month = [components month];
theParts.year = [components year];


Why keep them in a struct? The NSDateComponents object already has all the information you need, just pass it around your program. If you wanted to make this really easy you could actually add the component extraction logic to NSDate in a category. Like so:

In NSDate+MyComponents.h

@interface NSDate (MyComponents)
-(NSDateComponents *) components: (NSUInteger) unitFlags;
@end

In NSDate+MyComponents.c

@implementation NSDate (MyComponents)
-(NSDateComponents *) components: (NSUInteger) unitFlags {
    return [[NSCalendar currentCalendar] components: unitFlags fromDate: self];
}
@end

Caveat: I haven't actually compiled this since Im at work currently. Will verify the logic when I get home.

0

精彩评论

暂无评论...
验证码 换一张
取 消