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

*爱你&永不变心* 提交于 2019-11-28 06:24:06

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/39919415/is-it-possible-to-create-mutable-versions-of-objects-read-in-from-a-plist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!