-2

One must be blind not to see the difference with the above question.

I have a NSArray like

[
    {
        "NAME": "MyProduct1",
        "UUID": 4
    },
    {
        "NAME": "MyProduct2",
        "UUID": 10
    },
    {
        "NAME": "MyProduct3",
        "UUID": 18
    },
...
]

Now with a specific ID number I would like to get a dictionary containing only the concerned product. So with ID=18 it would be :

 {
  "NAME": "MyProduct3",
  "UUID": 18
 }

I'm trying to find an elegant solution, considering each UUID is unique in the array.

kursus
  • 1,396
  • 3
  • 19
  • 35
  • This is not at all the same question. It's about getting a NSArray from another NSArray with possible duplicate values, here we're talking getting a NSDictionary from a single (and unique, see UUID) value. – kursus Mar 22 '15 at 15:56
  • Any kind of argumentation would be welcome here. – kursus Mar 22 '15 at 16:13
  • Guys with great power comes great responsibility. Please read carefully next time. – kursus Mar 22 '15 at 16:42

1 Answers1

5

You can use a NSPredicate

NSArray *myArray = @[
    @{
        @"NAME": @"MyProduct1",
        @"UUID": @4
    },
    @{
        @"NAME": @"MyProduct2",
        @"UUID": @10
    },
    @{
        @"NAME": @"MyProduct3",
        @"UUID": @18
    }
];

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"UUID == 18"];
NSArray *filteredArray = [myArray filteredArrayUsingPredicate:predicate];
id firstFoundObject = filteredArray.firstObject;
NSLog(@"Result: %@", firstFoundObject);

And the result:

2015-03-22 17:15:06.468 Untitled[23770:2311273] Result: {
    NAME = MyProduct3;
    UUID = 18;
}

as described here: How to search an NSSet or NSArray for an object which has an specific value for an specific property?

Community
  • 1
  • 1
Steffen D. Sommer
  • 2,896
  • 2
  • 24
  • 47