尝试为NSError设置本地化描述时代码崩溃

时间:2012-03-06 10:28:21

标签: objective-c ios nserror

如果出现问题我正试图设置错误信息,但我得到了

This class is not key value coding-compliant for the key NSLocalizedDescription

这是我使用的代码

-(id)getMoneyFromAccount:(int) sum error:(NSError **)error
{
    if(self.balance - sum < 0)
    {
        NSDictionary *details = [NSDictionary dictionary];
        [details setValue:@"You don't have enough money" forKey:NSLocalizedDescriptionKey];
        *error = [NSError errorWithDomain:@"money" code:200 userInfo:details];
        return nil;
    }
    self.balance = self.balance - sum;
    return  [NSNumber numberWithInt:self.balance];
}

4 个答案:

答案 0 :(得分:8)

您正在致电setValue:forKey:,致电setObject:forKey:

[details setObject:@"You don't have enough money" forKey:NSLocalizedDescriptionKey];

此外,您必须从NSDictionary更改为NSMutableDictionary或在初始值设定项中设置值:

NSDictionary *details = [NSDictionary
    dictionaryWithObject:@"You don’t…"
    forKey:NSLocalizedDescriptionKey];

setValue:forKey:可以使用可变字典,但最好直接调用setObject:forKey:

答案 1 :(得分:1)

当您需要更改为初始化的NSError的localizedDescription时,您可以覆盖NSError类,如下所示:

@interface ValidationError : NSError

@property (nonatomic, strong) NSString *localizedDescription;
@end

答案 2 :(得分:0)

不,setValue:forKey:是正确的使用方法。也许这是因为您需要创建NSMutableDictionary而不是NSDictionary。

答案 3 :(得分:0)

您需要使用NSMutableDictionary或初始化程序来设置值。初始化后,无法更改NSDictionary。

NSDictionary* details = [NSDictionary dictionaryWithObject: @"..." 
                                                    forKey: NSLocalizedDescriptionKey];