I have a lot of functionality in my app that is date/time dependent (e.g. "if date is x, show y). I use [NSDate date] to get the current dat开发者_如何学编程e/time of the user. I can test functionality by manually changing the date/time on my iPhone but I'm wondering if there is a way to programatically overwrite the the current time so I can test in the simulator and more quickly.
Another way of doing it is to provide a custom implementation of +(NSDate *)date. You can swizzle this class method using JRSwizzle. Make a small category for the NSDate:
static NSTimeInterval seconds = 1300000000;
@interface NSDate (Fixed)
+ (NSDate *)fixedDate;
@end
@implementation NSDate (Fixed)
+ (NSDate *)fixedDate
{
return [NSDate dateWithTimeIntervalSince1970:seconds];
}
@end
Then in the code where you want to have fixed date do the following:
NSError *error;
[NSDate jr_swizzleClassMethod:@selector(date) withClassMethod:@selector(fixedDate) error:&error];
NSLog(@"Date:%@", [NSDate date]);
The log prints out this:
2011-09-01 11:35:27.844 tests[36597:10403] Date:2011-03-13 07:06:40 +0000
You can create NSDate objects with any date/time you want. Just run your code through a method to get "the current" time and inside this method either return the real date for production or some date of your choice for testing.
Create a category on NSDate
and override +[NSDate date]
method
+ (instancetype)date
{
return [NSDate dateWithTimeIntervalSince1970:100000]; // Replace with any date you want
}
dateByAddingTimeInterval:
Returns a new NSDate object that is set to a given number of seconds relative to the receiver.
- (id)dateByAddingTimeInterval:(NSTimeInterval)seconds
Parameters seconds The number of seconds to add to the receiver. Use a negative value for seconds to have the returned object specify a date before the receiver. Return Value A new NSDate object that is set to seconds seconds relative to the receiver. The date returned might have a representation different from the receiver’s.
source : the documentation :p
精彩评论