1

Is it possible to get an NSDictionary using KVC from a NSArray of CALayer based on key property name? I tried using -dictionaryWithValuesForKeys:, but that returns an NSArray. Any idea?

   NSArray *tempArray = [self.layer.sublayers copy];
   NSArray *ListName = [self.layer.sublayers valueForKey:@"name"];

   NSDictionary *tmpD= [tempArray dictionaryWithValuesForKeys:ListName];

Thanks

Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131
user519274
  • 1,074
  • 1
  • 11
  • 22

2 Answers2

5

Is this what you're asking about?

NSDictionary * layersByName = [NSDictionary dictionaryWithObjects:[self.layer.sublayers copy]
                                                          forKeys:[self.layer.sublayers valueForKey:@"name"]];

-[NSArray valueForKey:] returns an array formed by asking each object in the reciever for its own valueForKey:, using the same argument.

jscs
  • 63,694
  • 13
  • 151
  • 195
0

I don’t know of a way to do this directly with KVC. It’s pretty simple to do just by iterating over the array, though:

NSMutableDictionary *layersByName = [NSMutableDictionary dictionary];
for (CALayer *layer in self.layer.sublayers)
{
    [layersByName setObject:layer forKey:layer.name];
}
Noah Witherspoon
  • 57,021
  • 16
  • 130
  • 131