好吧所以我已经坚持了一段时间,即使这是一个简单的问题,我试图将NSDictionary添加到一个数组但是当在数组上调用addObject方法时程序崩溃声称我发送一个变异方法到一个不可变的对象。
我的代码如下:
- (IBAction)btnSaveMessage:(id)sender {
//Save The Message and Clear Text Fields
NSMutableDictionary *newMessageDictionary = [[NSMutableDictionary alloc] init];
[newMessageDictionary setObject:@"plist test title" forKey:@"Title"];
[newMessageDictionary setObject:@"plist subtitle" forKey:@"Subtitle"];
[newMessageDictionary setObject:@"-3.892119" forKey:@"Longitude"];
[newMessageDictionary setObject:@"54.191707" forKey:@"Lattitude"];
NSMutableArray *messagesArray =[[NSMutableArray alloc]init];
//Load Plist into array
NSString *messagesPath = [[NSBundle mainBundle] pathForResource:@"Messages"
ofType:@"plist"];
messagesArray = [NSArray arrayWithContentsOfFile:messagesPath];
[messagesArray addObject:newMessageDictionary]; //this causes crash
//write messagesarray to file
NSString *plistPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES) lastObject];
plistPath = [plistPath stringByAppendingPathComponent:@"usersMessages.plist"];
[messagesArray writeToFile:plistPath atomically:YES];
所以我理解我正在尝试添加编译器看到的不可变数组,但我将其声明为Mutable?
怎么回事? :(
答案 0 :(得分:1)
您正在使用此行中的NSMutableArray
覆盖NSArray
messagesArray = [NSArray arrayWithContentsOfFile:messagesPath];
类方法arrayWithContentsOfFile:
仅返回NSArray
而不是NSMutableArray
。
如果您希望文件的内容可变,您可以这样做:
NSMutableArray *messagesArray = [[NSArray arrayWithContentsOfFile:messagesPath] mutableCopy];
您可以删除之前的声明
NSMutableArray *messagesArray =[[NSMutableArray alloc]init];
现在
答案 1 :(得分:1)
您正在使用
重新初始化messagesArray[NSArray arrayWithContentsOfFile:messagesPath]
让它变得不可变。尝试:
[NSMutableArray arrayWithContentsOfFile:messagesPath];