[英]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.