在没有for循环的情况下获取另一个数组中每个对象的属性值数组 [英] Get array of property value of each object in another array without a for loop

查看:85
本文介绍了在没有for循环的情况下获取另一个数组中每个对象的属性值数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这可能是一个基本问题,但我似乎找不到答案.

This might be a basic question, but I can't seem to find an answer.

假设我有一个NSArray(carArray),其中包含某种类型的对象(Car).

Suppose I have an NSArray (carArray) with objects of a certain type (Car).

是否可以在不使用for循环迭代carArray的情况下获得具有这些对象的属性(颜色)的所有值的NSArray(colorArray)? (在.NET中为LINQ)

Is it possible to get an NSArray (colorArray) with all values of a property (color) of these objects without iterating carArray with a for loop? (cfr. LINQ in .NET)

NSMutableArray *colorList = [[NSMutableArray alloc] initWithCapacity:0];

for (Car *car in carArray)
{
    [colorList addObject:car.color];
}

提前谢谢.

推荐答案

是.假设您的对象采用的是 KVC/KVO协议.您可以获取以下属性的数组:

Yes. Assuming that your object is adopting the KVC/KVO protocol. You can get an array of the properties like:

NSArray *colorList = [carArray valueForKey:@"color"];

实际上,valueForKey:方法的作用是返回一个数组,该数组包含对每个数组对象使用 key 调用valueForKey:的结果. (摘自Apple在NSArray上的文档)

Actually, what valueForKey: method does, is to return an array containing the results of invoking valueForKey: using key on each of the array's objects. (From Apple's Documentation on NSArray)

这篇关于在没有for循环的情况下获取另一个数组中每个对象的属性值数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆