Update Value of Particular Key Inside NSarray

1.2k views Asked by At

I'm having NSArray like

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

In this in need to update/change array[0] "is_married" to false. Which means I need to update Kavin married status to false. How it is possible.

2

There are 2 answers

2
ERbittuu On BEST ANSWER

You can't update Value in NSArray, It is inmutable. But you can do something like this.

In Objective 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;

Here you get update array object.

In Swift

Array must be declare with 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")

Here you get update array object

0
Kavin Kumar Arumugam On

Finally got some perfect code:

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)!

Output will be like:

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