I have a NSSet
(e.g. "fruits") which consists of NSManagedObjects
and is created by using the following filtering code:
NSSet *fruits = [self.allFruits filteredSetUsingPredicate:
[NSPredicate predicateWithFormat:@"quantity > 10"];
Each of the fruits has the following properties (attributes): name
(e.g.: apple, orange, banana), color
(red, yellow, green) and quantity
(100, 20, 10).
What would be the most efficient way to create a NSDictionary
out of this NSSet
which contains the name
s of the fruits as the keys and the quantities
as the objects (e.g. key:object: apple: 100 orange: 20)?
This is how this could be done using block enumeration:
__block NSMutableDictionary *fruitsAndColors = [NSMutableDictionary dictionary];
[fruits enumerateObjectsUsingBlock:^(id fruit, BOOL *stop) {
[fruitsAndColors setObject:fruit.color forKey:fruit.name];
}];
Is there a more elegant way to accomplish the same?
Thank you!
Have you tried using a custom NSManagedObject subclass with a method that writes writes each object out to a dictionary with the keys and values that you want.
Then you can enumerate your NSSet and call this method on each object to create a collection of dictionaries.
I'm only giving you a general idea because you've asked a general question. If you try and write the code you can come back with any further problems that you face.