mreith
mreith

Reputation: 299

Handling class methods when sub-classing in objective-c

While attempting my first sub-class in Objective-C I have come across the following warning which I cannot seem to resolve. The call to decimalNumberWithMantissa gives a warning of "initialization from distinct Objective-C type".

#import <Foundation/Foundation.h>

@interface NSDecimalNumberSub : NSDecimalNumber {
}
@end

@implementation NSDecimalNumberSub
@end

int main (int argc, char *argv[]) {
    NSDecimalNumberSub *ten = [NSDecimalNumberSub 
          decimalNumberWithMantissa:10
          exponent:0
          isNegative:NO];
}

Does a class method have to be treated differently with a sub-class? Am I missing something simple? Any help would be appreciated.

Upvotes: 1

Views: 164

Answers (1)

Marc Charbonneau
Marc Charbonneau

Reputation: 40517

NSDecimalNumber defines the decimalNumberWithMantissa:... method to return an NSDecimalNumber, so you're going to get back an instance of the base class and not your custom subclass. You'll have to create your own convenience method to return an instance of your subclass, or just alloc and initialize it another way.

If you're writing your own class you can define a convenience method like that to return type id, and then use [[self alloc] init] when creating the instance to make your class safe for subclassing.

Upvotes: 3

Related Questions