user519274
user519274

Reputation: 1144

NSDictionary from NSArray using KVC

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

Upvotes: 1

Views: 265

Answers (2)

jscs
jscs

Reputation: 64002

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.

Upvotes: 5

Noah Witherspoon
Noah Witherspoon

Reputation: 57149

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];
}

Upvotes: 0

Related Questions