我如何子类化 NSDate? [英] How do I subclass NSDate?
问题描述
我第一次尝试对 NSDate 进行子类化以提供我需要的 2 个方法.编译正常,但在运行时我尝试访问它时出现错误.
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];
我收到错误
-[NSDate initWithTimeIntervalSinceReferenceDate:]: method only defined for
abstract class. Define -[myNSDate initWithTimeIntervalSinceReferenceDate:]!
有什么不同?
推荐答案
NSD 的回答是正确的,我就尽量简单地重申一下.NSDate
不是一个可以轻松子类化的简单类.这是一个 类簇,简而言之,当你得到一个 NSDate
类型的值时,它实际上是一个不同的私有类的实例,与 NSDate
.换句话说,<代码>的NSDate 代码>不是你想的东西的子类.
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
现在您可以调用[date doFoo]
.另请参阅类簇子类化教程 迈克·阿什.
Now you can call [date doFoo]
. See also a class cluster subclassing tutorial by Mike Ash.
这篇关于我如何子类化 NSDate?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!