从文件加载 NSNumbers 数组并使它们可变
我考虑过的一种方法是创建一个临时数组并将 NSNumbers 数组加载到其中,然后分配可变数组,然后如果加载的数组不是 nil 或空 addObject:[NSNumber numberWithInt :[[temparr objectAtIndex:i] intValue]],
但这似乎是一种迂回的做法。
这样我就可以修改应用程序中的数字和数组内容。
有没有更短、更切中要害的方法来做同样的事情?从某个地方加载数组/字典却发现它们的内容不可变是很常见的,我想学习最直接的方法。
One way I've considered is creating a temporary array and loading the array of NSNumbers
into it, then alloc the mutable array, then if loaded array is not nil or empty addObject:[NSNumber numberWithInt:[[temparr objectAtIndex:i] intValue]],
but it seems such a roundabout way of doing it.
This is so that I can modify the numbers and array contents in the app.
Is there a shorter, more to-the-point method of doing the same? It's quite common to load arrays/dicts from somewhere only to find their contents immutable, and I'd like to learn the most straightforward way.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您不能使
NSNumber
对象可变,它们在设计上是不可变的对象。如果您想制作数组的可变深层副本,即数组的可变副本及其内容的可变副本(如果可能的话;例如,在
NSNumber
的情况下,您不能),你可以这样做:You can not make
NSNumber
objects mutable, they are immutable objects by design.If you want to make a mutable deep copy of the array, that is, a mutable copy of the array and a mutable copy of its contents (when possible; for example, in the case of
NSNumber
s you can't), you can do something like this:您不能将 NSNumber 放入可变数组中并期望能够更改它们的值。请参阅问题中的代码以了解我使用的解决方法。
You cannot put NSNumbers in a mutable array and expect to be able to change their values. See the code in the question for the workaround I used.