mutate方法发送到不可变对象 [英] mutating method sent to immutable object
问题描述
当我使用这种方法第一次它工作正常,但当我第二次调用它时,我得到错误mutating方法发送到不可变对象。该问题符合addObject命令。
When I use this method first time it works fine, but when I called it second time I get the error "mutating method sent to immutable object". The problem is at line with "addObject" command.
-(IBAction) save: (id) sender{
NSMutableArray *placesT= [[NSUserDefaults standardUserDefaults] objectForKey:@"placesT"];
if (!placesT) {
placesT=[[[NSMutableArray alloc] init] autorelease];
}
[placesT addObject: [NSString stringWithFormat:@"%@", tagF.text] ];
NSUserDefaults *tUD=[NSUserDefaults standardUserDefaults];
[tUD setObject:placesT forKey:@"placesT"];
[tUD synchronize];
[self dismissModalViewControllerAnimated:YES];
}
推荐答案
由于NSUserDefaults的文档说:从NSUserDefaults返回的值是不可变的,即使你设置了一个可变对象作为值。每当你想更改从NSUserDefaults获取的集合,你必须得到不可变的版本,使一个 mutableCopy
,修改,并再次设置它。
As the documentation for NSUserDefaults says: "Values returned from NSUserDefaults are immutable, even if you set a mutable object as the value." Whenever you want to change a collection you get from NSUserDefaults you have to get the immutable version, make a mutableCopy
, modify that, and set it back again.
这篇关于mutate方法发送到不可变对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!