New method in subclassed class shows warning in Objective-c
I subclassed NSDate class and added my method 'myDate' under
@interface NSDa开发者_如何学Gote (NSDateAdditions) section.
When i want to use this method, I import "NSDateAdditions.h" and use it. The problem is that i always get warning "'NSDate' may not respond to 'myDate'"
Is there a way to get rid of this warning?
When you write:
@interface NSDate (NSDateAdditions)
you’re not subclassing NSDate
. Instead, you’re adding a category named NSDateAdditions
to the NSDate
class. By doing so, the class is still called NSDate
and the methods declared in the category are added to NSDate
.
You can declare class and/or instance methods in a category. For example:
// NSDate+NSDateAdditions.h
@interface NSDate (NSDateAdditions)
- (id)anInstanceMethod;
+ (id)aClassMethod;
@end
and:
// SomeImplementationFile.m
#import <UIKit/UIKit.h>
#import "NSDate+NSDateAdditions.h"
// in some method…
{
NSDate *someDate = [NSDate aClassMethod];
NSDate *anotherDate = [NSDate date];
id someResult = [anotherDate anInstanceMethod];
}
Without seeing your category declaration (and how you’re using it), it’s hard to tell what’s wrong with your code. One thing to check is whether you’ve declared a class or instance method — class methods are declared with +
whilst instance methods are declared with -
. When using a class method, you send a message to the class, namely NSDate
:
// Send a message to the class
NSDate *someDate = [NSDate aClassMethod];
When using an instance method, you send a message to a previously created instance:
// Create an instance
NSDate *anotherDate = [NSDate date];
// Send a message to the instance
id someResult = [anotherDate anInstanceMethod];
I'm sorry according to what you've written you have not subclassed NSDate. What you are doing is you're adding NSDateAdditions category. Even that way does not seem to be quite right as I don't understand "section" part there. The compiler should complain. You should do it this way instead:
@interface NSDateAdditions:NSDate
//declare your method here.
@end;
精彩评论