我的问题是,我的头文件中定义了一个类属性为NSMutableArray的属性,但是当我尝试修改数组元素之一(NSDictionary)时,出现以下运行时错误:

2013-01-16 14:17:20.993 bondaculous [5674:c07] *终止应用程序到期
未捕获的异常“NSInternalInconsistencyException”,原因:
'-[__ NSCFArray replaceObjectAtIndex:withObject:]:发送的变异方法
到不可变的对象”

标头声明:

//  BudgetViewController.h

#import <UIKit/UIKit.h>

@interface BudgetViewController : UIViewController <UITableViewDataSource, UITableViewDelegate>
- (IBAction)afterTaxIncomeEditingDidEnd:(id)sender;
@property (strong, nonatomic) NSMutableArray *budgetArray;
@property (strong, nonatomic) IBOutlet UITextField *afterTaxIncome;
@property (strong, nonatomic) IBOutlet UITableView *budgetTableView;

@end

产生错误的方法:
-(void)applyCCCSWeights
{
    NSMutableDictionary *valueDict;
    NSString *newAmount;

    for (id budgetElement in [self budgetArray]) {
        valueDict = [[NSMutableDictionary alloc] initWithDictionary:budgetElement];
        newAmount = [NSString stringWithFormat:@"%0.2f", [[self afterTaxIncome].text floatValue] * [[budgetElement objectForKey:@"cccs_weight"] floatValue]];
        [valueDict setValue:newAmount forKeyPath:@"amount"];

        [[self budgetArray] replaceObjectAtIndex:0 withObject:valueDict];
        NSLog(@"%0.2f (%0.2f)", [[budgetElement objectForKey:@"amount"] floatValue], [[self afterTaxIncome].text floatValue] * [[budgetElement objectForKey:@"cccs_weight"] floatValue]);
    }

    [self.budgetTableView reloadData];
}

//请注意,上面的replaceObjectAtIndex:0只是一个占位符。这将被替换为正确的索引。

最佳答案

在您的init方法中,输入以下内容:

budgetArray = [[NSMutableArray alloc] init];

另外,为什么不使用字典和数组文字语法呢?
-(void)applyCCCSWeights {
    NSMutableDictionary *valueDict;
    NSString *newAmount;

    for (NSDictionary *budgetElement in [self budgetArray]) {
        valueDict = [budgetElement mutableCopy];
        newAmount = [NSString stringWithFormat:@"%0.2f", [[self afterTaxIncome].text floatValue] * [budgetElement[@"cccs_weight"] floatValue]];
        valueDict[@"amount"] = newAmount;

        _budgetArray[0] = valueDict;
        NSLog(@"%0.2f (%0.2f)", [budgetElement[@"amount"] floatValue], [[self afterTaxIncome].text floatValue] * [budgetElement[@"cccs_weight"] floatValue]);
    }

    [self.budgetTableView reloadData];
}

注意[[self budgetArray] replaceObjectAtIndex:0 withObject:valueDict];
变为:_budgetArray[0] = valueDict;

10-06 03:59