Search code examples
iosobjective-cnsarray

Find a value in NSArray [json]


I have an array of json objects like this:

array : (
    {
expiryDate = "2016-04-22T00:00:00Z";
    id = "4dad2aeb-efa3-45ca-8d1a-7382851c56d7";
    name = "demo1";
    value = 200;
},
    {
    expiryDate = "2016-06-20T00:00:00Z";
    id = "28e0df69-3e8f-413d-a6c6-3d4cdad544f9";
    name = "Demo 2";
    value = 200;
},
    {
    expiryDate = "2016-06-19T00:00:00Z";
    id = "2e1f452e-ba53-4d4c-a4fa-e15442057b8b";
    name = "demo3";
    value = 214;
})

and I have a string string = 2e1f452e-ba53-4d4c-a4fa-e15442057b8b

I have to check wether the NsString is present in NSArray or not. I am thinking to convert array into dictionary and do searching. Please help me in this part.


Solution

  • Suppose your NSArray is array. Use below lines of code.

     BOOL flag= [array valueForKey:@"id"] containsObject: @"2e1f452e-ba53-4d4c-a4fa-e15442057b8b"];
    
     if(flag){
     NSInteger index=[array valueForKey:@"id"] indexOfObject: @"2e1f452e-ba53-4d4c-a4fa-e15442057b8b"];
     NSString *str = [array valueForKey:@"id"]objectAtIndex:index];
    }