3

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.

2
  • I’ve fixed one typo in the declaration of MyClass: you need to declare sampleName as NSString * instead of NSString. I’ve also replaced foreach with for. Commented Jun 4, 2011 at 9:18
  • Thanks, I came back to edit it and found you had already answered :) Commented Jun 4, 2011 at 9:35

1 Answer 1

4

Use Key-Value Coding:

NSArray *stringArray = [myArray valueForKey:@"sampleName"];
Sign up to request clarification or add additional context in comments.

1 Comment

thanks so much @Bavarious, especially for the quick response. It took me longer to test it out than for you to answer it. I love this forum!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.