Reputation: 3764
I've created a helpers category for NSDate (NSDate+Helpers). Here is a caching for the calendar object I'm going to use inside the category implementation:
static NSCalendar* currentCalendar = nil;
@implementation NSDate (Helpers)
+(void)initialize{
currentCalendar = [NSCalendar currentCalendar];
}
@end
The problem is that my application doesn't starts anymore. I see only black screen. I would like to know what I am doing wrong. You can get same problem on clean test project.
Upvotes: 0
Views: 191
Reputation: 9168
When you use a category to override an existing method, you overwrite the original implementation, so NSDate
's original +initialize
method never gets executed. In this case, it looks like it's doing something in that method that's necessary for its own internal functionality, and this is breaking your app.
Even if this is not the issue, overriding the +initialize
method is a bad idea, and doing any custom object instantiation there is an especially bad idea.
Try initialising the calendar object somewhere else, e.g. in applicationDidFinishLaunchingWithOptions:
in your app's delegate.
Another thing you can do is implement the calendar as a singleton in your category, like so:
@implementation NSDate (Helpers)
- (NSCalendar *)myCurrentCalendar {
static NSCalendar *currentCalendar; // static property
static dispatch_once_t onceToken; // token for dispatch
dispatch_once(&onceToken, ^{
currentCalendar = [NSCalendar currentCalendar]; // initialise
});
return currentCalendar; // return the calendar
}
Then, when you need to use it, you access it as [NSDate myCurrentCalendar]
. This will initialise the calendar the first time you call this method, and on subsequent calls to the method will simply immediately return the calendar.
Upvotes: 2