Libor Zapletal
Libor Zapletal

Reputation: 14102

iOS Arrays with custom classes to arrays with NSStrings

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]];

Upvotes: 1

Views: 65

Answers (3)

Paulw11
Paulw11

Reputation: 114975

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

Upvotes: 3

Trenskow
Trenskow

Reputation: 3793

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.

Upvotes: 2

cutsoy
cutsoy

Reputation: 10251

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];

Upvotes: 2

Related Questions