How do I subclass NSDate?

我与影子孤独终老i 提交于 2019-11-30 17:51:25

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!