是否可以创建从plist读入的可变对象版本 [英] Is it possible to create mutable versions of objects read in from a plist

查看:109
本文介绍了是否可以创建从plist读入的可变对象版本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在阅读我的应用程序中的一个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"];

我收到错误' - [__ NSCFDictionary removeObjectForKey:]:mutating当我尝试更改字典值时,发送到不可变对象'的方法。如果由plist读入的NSDictionary是不可变的,则该错误是有意义的。

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.

是否有任何方法可以从plist中读取内容并确保读取任何数组或词典在可变版本中?

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

推荐答案

最简单的方法是使用 NSPropertyListSerialization 并传递适当的选项来获取可变容器。

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.

这段代码将加载plist并返回一个可变数组,每个包含的数组和字典也都是可变的。

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

这篇关于是否可以创建从plist读入的可变对象版本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆