How can I subclass NSDate?

I first tried subClassed NSDate to give it 2 methods that I need. It compiles fine, but at runtime I try to access it. I get an error message.

Suppose I just want the current date to not be changed in a subclass:

[myNSDate date]; 

I get an error

 -[NSDate initWithTimeIntervalSinceReferenceDate:]: method only defined for abstract class. Define -[myNSDate initWithTimeIntervalSinceReferenceDate:]! 

what else?

+4
source share
2 answers

Answers NSDs corect, I just try to repeat in simple terms. NSDate is not a simple class that you could easily subclass. Its a cluster of classes , which, in short, when you get a value of type NSDate , its an actual instance of another private class that has the same interface as NSDate . In other words, NSDate is not what you would like to subclass.

If you just want to add methods (not instance variables), you can easily do this using the category:

 @interface NSDate (MyExtensions) - (void) doFoo; @end @implementation NSDate (MyExtensions) - (void) doFoo { NSLog(@"Foo"); } @end 

Now you can call [date doFoo] . See also the tutorial on cluster cluster classes from Mike Ash.

+7
source

NSDate is a class cluster, and you should not make any assumptions about the base type returned by its methods, and do not try to subclass it unless you know exactly what you are doing. If you want to expand it, do it with a category.

+1
source

Source: https://habr.com/ru/post/1307212/


All Articles