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"];
NSString *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:
Also, there are a few other points that can be taken into consideration to improve this method:
NSStringas type; use anenumNSDateFormatteron each call to the method; instead use astaticvariable in the method