How do I subclass NSDate?

杀马特。学长 韩版系。学妹 提交于 2019-11-30 21:51:52

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.

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.

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