1

I have my own class with several properties and I have them in NSArray. I need to use them for method which takes NSArray of strings. So I am asking what is best aproach to get array with strings from my array which has custom classes. I can create second array and use it but I think there could be better way. I need to have it for different custom classes (from one, I want to use for example name property to new NSArray, in second title property and so).

I hope I explained well but I tried it once more on example:

NSArray *arrayWitCustomClasses =  ... fill with custom classes;
// setValues method takes NSArray with NSStrings
// when arrayWithCustomClasses used it returns copyWithZone: error on custom class
[someObject setValues:[arrayWithCustomClasses toArrayWithStrings]];

3 Answers 3

3

As long as your object exposes the required values as NSString properties you can use the valueForKey method of NSArray.

For example

NSArray *arrayOfTitles=[arrayWithCustomClasses valueForKey:@"title"];

NSArray *arrayOfNames=[arrayWithCustomClasses valueForKey:@"name"];

Or

[someObject setValues:[arrayWithCustomClasses valueForKey:@"title"]];

and so on

Sign up to request clarification or add additional context in comments.

3 Comments

I might be wrong, but I think you need to use valueForKeyPath: ?
valueForKey: Returns an array containing the results of invoking valueForKey: using key on each of the array's objects.
This is what I was looking for. It's a little better then @Trenskow because I can use properties with valueForKey.
2
NSMutableArray *strings = [NSMutableArray array];

for (NSObject *item in arrayWithCustomClasses) {
    /* You can use a different property as well. */
    [strings addObject:item.description];
}

[someObject setValues:strings.copy];

Comments

2

Like @Tim says, but you could shorten it by just using:

[someObject setValues:[arrayWithCustomClasses valueForKey:@"description"]];

Same result. One line of code.

Then implement the description method of your custom classes to return whatever properties and formatting you want.

Comments

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.