我的问题是我有一个类型为 的类属性NSMutableArray
,如我的头文件中所定义,但是当我尝试修改其中一个数组元素(an NSDictionary
)时,我收到以下运行时错误:
2013-01-16 14:17:20.993 债务[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
上面只是一个占位符。这将替换为正确的索引。