0

Ok so I have been stuck on this for a while even though it's a simple problem, I am trying to add an NSDictionary to an array however when calling the addObject method on the array the program crashes claiming I am sending a mutating method to an immutable object.

my code looks like:

    - (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];

So I understand that I am trying to add to what the compiler see's as an immutable array but I declared it as Mutable?

Whats going on? :(

2 Answers 2

1

You are re-initializing messagesArray with

[NSArray arrayWithContentsOfFile:messagesPath]

Making it not mutable. Try:

[NSMutableArray arrayWithContentsOfFile:messagesPath];
Sign up to request clarification or add additional context in comments.

1 Comment

You just needed someone to be your cocker spaniel.
1

You are overwriting your NSMutableArray with an NSArray in this line

messagesArray = [NSArray arrayWithContentsOfFile:messagesPath];

The class method arrayWithContentsOfFile: is returning just an NSArray and not an NSMutableArray.

If you want the content of the file mutable you can do this:

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

and you can remove the previous declaration

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

now.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.