0

好的,所以即使这是一个简单的问题,我也已经坚持了一段时间,我正在尝试将 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];

所以我知道我正在尝试将编译器视为不可变数组的内容添加到其中,但我将其声明为可变数组?

这是怎么回事?:(

4

2 回答 2

1

您正在NSMutableArrayNSArray这一行中的 a 覆盖您的

messagesArray = [NSArray arrayWithContentsOfFile:messagesPath];

类方法arrayWithContentsOfFile:只返回一个NSArray而不是一个NSMutableArray

如果您希望文件的内容可变,您可以这样做:

NSMutableArray *messagesArray = [[NSArray arrayWithContentsOfFile:messagesPath] mutableCopy];

你可以删除之前的声明

 NSMutableArray *messagesArray =[[NSMutableArray alloc]init];

现在。

于 2013-05-02T16:27:04.070 回答
1

您正在重新初始化 messagesArray

[NSArray arrayWithContentsOfFile:messagesPath]

使其不可变。尝试:

[NSMutableArray arrayWithContentsOfFile:messagesPath];
于 2013-05-02T16:27:32.467 回答