tags:

views:

111

answers:

1

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.

+3  A: 

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.

Marc Charbonneau
Convenience constructors generally return a dynamically-typed value (type id) for this reason; NSDecimalNumber is an exception, and I consider it to be in error. For example, [NSArray array] is typed as id, and [NSMutableArray array] would return an instance of NSMutableArray.
jmah