简体   繁体   中英

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

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM