Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
892 views
in Technique[技术] by (71.8m points)

ios - Is it possible to create mutable versions of objects read in from a plist

I'm reading into my application a plist which at the top level is an array. It's simple enough to make sure the array starts as mutable

self.plistData = [[NSArray arrayWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"myDataSource" ofType:@"plist"]] mutableCopy];

Within each element of the array is another array, each of those contains a dictionary.

Based on a tablecell selection I'm changing attributes for the dictionary at the selected index:

[self.cellDescriptors[indexPath.section][indexOfTappedRow] setValue:@"YES" forKey: @"isSelected"];

I'm getting the error '-[__NSCFDictionary removeObjectForKey:]: mutating method sent to immutable object' when I attempt to change a dictionary value. The error makes sense if the NSDictionary read in by the plist is immutable.

Is there any way to read in content from a plist and make sure any arrays or dictionaries are read in as mutable versions?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The simplest approach is to use NSPropertyListSerialization and passing the proper options to get mutable containers.

NSString *path = [[NSBundle mainBundle] pathForResource:@"myDataSource" ofType:@"plist"];
NSData *data = [NSData dataWithContentsOfFile:path];
NSMutableArray *array = [NSPropertyListSerialization propertyListWithData:data options:NSPropertyListMutableContainers format:nil error:nil];
self.plistData = array;

Ideally you will make use of the error parameter and do proper error checking but this will get you started.

This code will load the plist and return a mutable array and every contained array and dictionary will also be mutable.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...