Incompatible pointer type sending 'Class'

2019-07-09 03:35发布

问题:

I have an NSDate category with following method

@implementation NSDate (DateUtility)

+(NSString *)dateTimeStringForDB {
    NSDateFormatter *dateFormatForDB = [[NSDateFormatter alloc] init];
    [dateFormatForDB setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *aDateStr= [dateFormatForDB stringFromDate:self];
    [dateFormatForDB release];
    return aDateStr;    
}
@end

with this definition I receive a warning .

Incompatible pointer type sending 'Class' to parameter of type 'NSDate *'

However type casting self before assign it as argument suppresses this warning.

+(NSString *)dateTimeStringForDB
{
    NSDateFormatter *dateFormatForDB = [[NSDateFormatter alloc] init];
    [dateFormatForDB setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    NSString *aDateStr= [dateFormatForDB stringFromDate:(NSDate*)self];
    [dateFormatForDB release];
    return aDateStr;    
}

Can we really not pass self as an argument in a category without typecasting it ? What is this feature dependent on , the compiler ? Looking for an answer before actually posting it as a question on SO I came across this, however I am still not clear as to what goes behind the scene.

回答1:

You have created a class method, I suspect you really want an instance method. I assume you want to convert an instance of an NSDate (ie an object) into an NSString representation. Currently you are trying to convert the actual NSDate class into an NSString representation.

Change

+(NSString *)dateTimeStringForDB {

to

-(NSString *)dateTimeStringForDB {