Getting an array of a property from an object array

南笙酒味 提交于 2019-11-26 18:36:42

问题


I need to extract an array of a single property from a custom object array. eg.

@interface MyClass : NSObject 
{
    int sampleNumber;
    NSString *sampleName;
}

I have an array of MyClass instances called myArray. I want to then get an array of the sampleName strings. Is there a way to do it without stepping through the whole array like this:

NSMutableArray *stringArray;

for (MyClass *thisInstance in myArray) 
{    
    [stringArray addObject:thisInstance.sampleName];
}

I attempted to search for a similar question in Objective-C but found it only in the PHP and LINQ sections.


回答1:


Use Key-Value Coding:

NSArray *stringArray = [myArray valueForKey:@"sampleName"];


来源:https://stackoverflow.com/questions/6235856/getting-an-array-of-a-property-from-an-object-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!