我正在尝试创建扩展NSDecimalNumber的Price类,但是当尝试分配和插入它时,它会引发异常。你知道什么是问题吗?
*** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: 'Did you forget to nest alloc and initWithString: ?'Price.h
#import <Foundation/Foundation.h>
@interface Price : NSDecimalNumber
+ (Price*)priceWithString:(NSString*)val;
@endPrice.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,则是相同的例外。我放弃了这个..。
发布于 2014-01-25 19:10:05
NSDecimalNumber继承了NSNumber,这是一个https://developer.apple.com/library/ios/documentation/general/conceptual/CocoaEncyclopedia/ClassClusters/ClassClusters.html#//apple_ref/doc/uid/TP40010810-CH4。这使得继承NSDecimalNumber变得非常困难,因为对于这种继承有许多额外的要求。根据苹果公司的文档,你的班级需要
在您的例子中,您的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对象的地方。当你错误地忽视货币时,这有可能防止愚蠢的错误,所以这可能是一个很好的安全措施。
https://stackoverflow.com/questions/21354923
复制相似问题