The problem is that dateToRound
is being passed in as a reference to one object and you are setting it to a reference to a different object. The original object is now abandoned and has been leaked.
You should create a new NSDate * and return it instead of reassigning dateToRound
.
Sample code:
-(NSDate*)roundTo15:(NSDate*)dateToRound {
int intervalInMinute = 15;
// Create a NSDate object and a NSDateComponets object for us to use
NSDateComponents *dateComponents = [[NSCalendar currentCalendar] components:NSMinuteCalendarUnit fromDate:dateToRound];
// Extract the number of minutes and find the remainder when divided the time interval
NSInteger remainder = [dateComponents minute] % intervalInMinute; // gives us the remainder when divided by interval (for example, 25 would be 0, but 23 would give a remainder of 3
// Round to the nearest 5 minutes (ignoring seconds)
NSDate *roundedDate = nil;
if (remainder >= intervalInMinute/2) {
roundedDate = [dateToRound dateByAddingTimeInterval:((intervalInMinute - remainder) * 60)]; // Add the difference
} else if (remainder > 0 && remainder < intervalInMinute/2) {
roundedDate = [dateToRound dateByAddingTimeInterval:(remainder * -60)]; // Subtract the difference
} else {
roundedDate = [[dateToRound copy] autorelease];
}
return roundedDate;
}