繁体   English   中英

继承NSDecimalNumber

[英]Inheriting NSDecimalNumber

我正在尝试创建扩展NSDecimalNumber的Price类,但是在尝试对其进行分配和初始化时会引发异常。 知道有什么问题吗?

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

价格.h

#import <Foundation/Foundation.h>

@interface Price : NSDecimalNumber
+ (Price*)priceWithString:(NSString*)val;
@end

价格.m

#import "Price.h"

@implementation Price
- (NSString *)description {
    return [[super description] stringByAppendingString:@" €"];
}
+ (Price*)priceWithString:(NSString*)val {
    return [[Price alloc] initWithString: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对象的地方。 当您错误地忽略货币时,这有可能防止愚蠢的错误,因此这可能是一个很好的安全措施。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM