Objective c 继承小数

Objective c 继承小数,objective-c,class,inheritance,extend,nsdecimalnumber,Objective C,Class,Inheritance,Extend,Nsdecimalnumber,我试图创建扩展NSDecimalNumber的Price类,但在尝试alloc和init时,它引发了异常。知道什么是问题吗 *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Did you forget to nest alloc and initWithString: ?' 价格 #import <Foundation/Foundation.h> @inter

我试图创建扩展NSDecimalNumber的Price类,但在尝试alloc和init时,它引发了异常。知道什么是问题吗

*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Did you forget to nest alloc and initWithString: ?'
价格

#import <Foundation/Foundation.h>

@interface Price : NSDecimalNumber
+ (Price*)priceWithString:(NSString*)val;
@end
编辑:
即使是光秃秃的班级也不行。如果我扩展NSDecimalNumber,然后尝试执行alloc init,则会出现相同的异常。我放弃了这个…

NSDecimalNumber
继承了
NSNumber
,这是一个很好的选择。这使得继承
NSDecimalNumber
非常困难,因为这种继承有许多额外的要求。根据Apple文档,您的类需要

  • 是集群抽象超类的子类
  • 声明自己的存储
  • 重写超类的所有初始值设定项方法
  • 重写超类的基本方法(如下所述)
在您的情况下,您的
Price
类需要重新实现大量的
NSDecimalNumber
,这可能是太多的工作了

更好的方法是将
NSDecimalNumber
嵌套在
Price
类中,并添加一个方法来获取其数值,如下所示:

@interface Price : NSObject

/// Represents the numeric value of the price
@property (nonatomic, readonly) NSDecimalNumber *valueInLocalCurrency;

/// Represents the pricing currency
@property (nonatomic, readonly) NSString *currencyCode;

/// Creates an immutable Price object
-(id)initWithPriceInLocalCurrency:(NSDecimalNumber*)price andCurrencyCode:(NSString*)currencyCode;

@end

一旦此决定的结果是,您不能再将
Price
对象发送到需要
NSDecimalNumber
对象的地方。当您错误地忽略货币时,这有可能防止愚蠢的错误,因此这可能是一个很好的安全措施。

NSDecimalNumber
继承了
NSNumber
,这是一种安全措施。这使得继承
NSDecimalNumber
非常困难,因为这种继承有许多额外的要求。根据Apple文档,您的类需要

  • 是集群抽象超类的子类
  • 声明自己的存储
  • 重写超类的所有初始值设定项方法
  • 重写超类的基本方法(如下所述)
在您的情况下,您的
Price
类需要重新实现大量的
NSDecimalNumber
,这可能是太多的工作了

更好的方法是将
NSDecimalNumber
嵌套在
Price
类中,并添加一个方法来获取其数值,如下所示:

@interface Price : NSObject

/// Represents the numeric value of the price
@property (nonatomic, readonly) NSDecimalNumber *valueInLocalCurrency;

/// Represents the pricing currency
@property (nonatomic, readonly) NSString *currencyCode;

/// Creates an immutable Price object
-(id)initWithPriceInLocalCurrency:(NSDecimalNumber*)price andCurrencyCode:(NSString*)currencyCode;

@end

一旦此决定的结果是,您不能再将
Price
对象发送到需要
NSDecimalNumber
对象的地方。这有可能防止错误地忽略货币时出现愚蠢的错误,因此,这可能是一个很好的安全措施。

应该使用
instancetype
/
self
Price
类中的
initithString:
方法在哪里?应该使用
instancetype
/
self
Price
类中的
initithString:
方法在哪里?
返回[超级初始化字符串:str]
?当然,除非他需要一些自定义初始化。我认为这不是问题所在。如果他不重写它,将调用默认实现。我错了,您是对的:@nhgrif我认为您需要在指定的初始值设定项中指定
self
。您可以将其折叠成一行,
返回self=[super initWithString:str];
但我认为赋值必须存在。@dasblinkenlight:“我认为您需要在指定的初始值设定项中赋值self。”不。仅仅为了返回它而赋值给局部变量(
self
)是没有意义的。
返回[super initWithString:str]
?当然,除非他需要一些自定义初始化。我认为这不是问题所在。如果他不重写它,将调用默认实现。我错了,您是对的:@nhgrif我认为您需要在指定的初始值设定项中指定
self
。您可以将其折叠成一行,
返回self=[super initWithString:str];
但我认为赋值必须在那里。@dasblinkenlight:“我认为您需要在指定的初始值设定项中赋值self。”不。仅仅为了返回它而赋值给局部变量(
self
)是没有意义的。