更新NSarray内部特定键的值

时间:2016-12-23 07:25:40

标签: ios swift nsarray nsobject

我正在使用NSArray

    array =  [
  {
    "name": "Kavin",
    "Age": 25,
    "is_married": "true"
  },
  {
    "name": "Kumar",
    "Age": 25,
    "is_married": "false"
  }
]

在此需要更新/更改数组[0]“is_married”为false。这意味着我需要将Kavin结婚状态更新为false。怎么可能。

2 个答案:

答案 0 :(得分:1)

你无法在NSArray中更新Value,它是不可改变的。 但你可以这样做。

在目标C

NSArray *array = // your array

NSMutableArray *arrayM = [array mutableCopy];

NSMutableDictionary *dic = (NSMutableDictionary*)arrayM.firstObject;
[dic setObject:@"false" forKey:@"is_married"];

[arrayM replaceObjectAtIndex:0 withObject:dic];

array = arrayM;

这里有更新数组对象。

在Swift中

数组必须声明为var not let。

var array =  [
        [
            "name" : "Kavin",
            "Age": 25,
            "is_married": "true"
        ],
        [
            "name" : "Kumar",
            "Age" : 25,
            "is_married": "false"
        ]]

    array[0].updateValue("false", forKey: "is_married")

这里有更新数组对象

答案 1 :(得分:-1)

最后得到了一些完美的代码:

let DuplicateArray: NSArray = array
let DuplicateMutableArray: NSMutableArray = []
DuplicateMutableArray.addObjectsFromArray(DuplicateArray as [AnyObject])
var dic = (DuplicateMutableArray[0] as! [NSObject : AnyObject])
dic["is_married"] = "false"
DuplicateMutableArray[self.SelectedIndexPath] = dic
array = []
array = (DuplicateMutableArray.copy() as? NSArray)!

输出将如下:

array =  [
  {
    "name": "Kavin",
    "Age": 25,
    "is_married": "false"
  },
  {
    "name": "Kumar",
    "Age": 25,
    "is_married": "false"
  }
]