问题
I first time tried to subClassed an NSDate to give it 2 methods that I need. Compiles fine, but in runtime I try to access it I get an error.
Lets say I just want the current date which is unmodified in the subClass:
[myNSDate date];
I get the error
-[NSDate initWithTimeIntervalSinceReferenceDate:]: method only defined for
abstract class. Define -[myNSDate initWithTimeIntervalSinceReferenceDate:]!
what is different?
回答1:
NSD’s answer corect, I’ll just try to reiterate in simple terms. NSDate
is not a simple class you could easily subclass. It’s a class cluster, which in short means that when you get a value of type NSDate
, it’s actually instance of a different, private class that has the same interface as NSDate
. In other words, NSDate
is not something you would want to subclass.
If you just want to add methods (not instance variables), you can easily do that using a category:
@interface NSDate (MyExtensions)
- (void) doFoo;
@end
@implementation NSDate (MyExtensions)
- (void) doFoo {
NSLog(@"Foo");
}
@end
Now you can call [date doFoo]
. See also a class cluster subclassing tutorial by Mike Ash.
回答2:
NSDate is a class cluster and you should not make any assumptions about the underlying type its methods return, nor should you attempt to subclass it unless you know exactly what you're doing. If you want to extend it, do it with a category.
来源:https://stackoverflow.com/questions/2657275/how-do-i-subclass-nsdate