在没有for循环的情况下获取另一个数组中每个对象的属性值数组

时间:2021-03-06 16:45:25

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

这可能是一个基本问题,但我似乎无法找到答案。

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

假设我有一个NSArray(carArray)与某种类型的对象(Car)。

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)

是否可以获得具有这些对象的属性(颜色)的所有值的NSArray(colorArray),而无需使用for循环迭代carArray? (cfr.LINQ in .NET)

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

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

Thanks in advance.

提前致谢。

3 个解决方案

#1


76  

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

是。假设您的对象采用KVC / KVO协议。您可以获得一系列属性,例如:

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

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)

实际上,valueForKey:方法的作用是返回一个数组,其中包含调用valueForKey的结果:在每个数组的对象上使用键。 (来自Apple关于NSArray的文档)

#2


15  

Yes. You can do that without iterating it.

是。你可以做到这一点,而无需迭代它。

NSArray *colorArray = [carArray valueForKeyPath:@"@distinctUnionOfObjects.color"];

#3


-1  

You can use the NSSet to get the colours:

您可以使用NSSet获取颜色:

NSSet *NScolors = [NSSet setWithArray:[carArray valueForKey:@"color"]];
NSArray *colors = [NScolors allObjects];

#1


76  

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

是。假设您的对象采用KVC / KVO协议。您可以获得一系列属性,例如:

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

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)

实际上,valueForKey:方法的作用是返回一个数组,其中包含调用valueForKey的结果:在每个数组的对象上使用键。 (来自Apple关于NSArray的文档)

#2


15  

Yes. You can do that without iterating it.

是。你可以做到这一点,而无需迭代它。

NSArray *colorArray = [carArray valueForKeyPath:@"@distinctUnionOfObjects.color"];

#3


-1  

You can use the NSSet to get the colours:

您可以使用NSSet获取颜色:

NSSet *NScolors = [NSSet setWithArray:[carArray valueForKey:@"color"]];
NSArray *colors = [NScolors allObjects];