views:

94

answers:

2

Hi,

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?

+2  A: 

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.

Azeem.Butt
Hi NSD, don't understand your response
iFloh
Of course you didn't.
Azeem.Butt
That’s a bit harsh, but essentially true. iFloh, read something about categories in Objective-C. They will probably solve your problem.
zoul
+2  A: 

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.

zoul
Hi Zoul, thanks for your explanation and URL. Haven't come accross categories yet. How simple it can be :)
iFloh