开发者

iPhone simple method definition and calling the current date/time

I'm very new to iPhone development, and I'm trying to write a function which will accept one parameter, and return the current date/month and store it in a variable.

But I'm getting a (null) value with NSLog.

Method:

-(NSString *) getNowDateMonth:(NSString *)type {

    NSDate *now = [[NSDate alloc] init];

    if (type==@"month") {
        NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
        [monthFormat setDateFormat:@"MM"];
        NSString *theMonth = [monthFormat stringFromDate:now];
        [monthFormat release];
        return theMonth;
    } else if (type==@"day") {
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"dd"];
        NSStrin开发者_运维技巧g *theDate = [dateFormat stringFromDate:now];
        //int setDate = theDate;
        [dateFormat release];
        return theDate;
    }
    [now release];
    return NULL;
}

Calling the function to get value:

NSString *month = [self getNowDateMonth:@"month"];
NSLog(@"%@", month);

Am I going about this the right way?


First of all, compare the strings using [@"month" isEqualToString:type], because two strings containing the same text ("month") may not be equal by the == operator. == checks if they're the same string object, not strings object with the same contents.

Second of all, you're leaking the date when returning the month or day (not releasing now). You should use [NSDate date]; instead of [[NSDate alloc] init].

To sum up, a suggested better version of this method would be:

-(NSString *) getNowDateMonth:(NSString *)type {
    NSDate *now = [NSDate date];
    if ([@"month" isEqualToString:type]) {
        NSDateFormatter *monthFormat = [[NSDateFormatter alloc] init];
        [monthFormat setDateFormat:@"MM"];
        NSString *theMonth = [monthFormat stringFromDate:now];
        [monthFormat release];
        return theMonth;
    } else if ([@"day" isEqualToString:type]) {
        NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
        [dateFormat setDateFormat:@"dd"];
        NSString *theDate = [dateFormat stringFromDate:now];
        [dateFormat release];
        return theDate;
    } else {
        return nil;
    }
}

Also, there are a few other points that can be taken into consideration to improve this method:

  • do not use NSString as type; use an enum
  • do not allocate NSDateFormatter on each call to the method; instead use a static variable in the method


You want to use NSDateComponents to reliably and easily extract unit information i.e. month, day, week etc from an NSDate.

See Date and Time Programming Guide for Cocoa.

Dates are a deceptively complex programing problem so Cocoa has a fully developed set of classes for dealing with them. However, the learning curve is a bit steep.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜