somerk
somerk

Reputation: 51

Sorting NSArray Using Descriptors

I have two arrays, I want to print values by names and alias. They are NSString values.

I`m a beginner in obj-c. I will be glad to any help.

And I’ll add everything you need to understand the cause of the problem, thanks!

NSArray <VBHuman*> * arrayOfHumans = [NSArray arrayWithObjects:
                          human, cycler, runner, swimmer, boxer,
                          nil];

NSArray <VBAnimal*> * arrayOfAnimals = [NSArray arrayWithObjects:
                           animal, dog, cat, hamster,
                           nil];

NSArray* newArray = @[];
newArray = [newArray arrayByAddingObjectsFromArray:arrayOfHumans];
newArray = [newArray arrayByAddingObjectsFromArray:arrayOfAnimals];


[newArray sortedArrayUsingDescriptors:
 @[
   [NSSortDescriptor sortDescriptorWithKey:@"name" ascending:YES],
   [NSSortDescriptor sortDescriptorWithKey:@"alias" ascending:YES]
   ]];

In results it doesn't work, it has type following:

[<VBAnimal 0x6000002520f0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.

Upvotes: 1

Views: 53

Answers (1)

Caleb
Caleb

Reputation: 125007

The error message tells you what's wrong:

[<VBAnimal 0x6000002520f0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key name.

When you use -sortedArrayUsingDescriptors:, NSArray uses the keys you give it to get values from the objects it's comparing in order to decide how to order the objects. If it can't determine the order from the first descriptor (because the values the objects return are the same), it moves on to the next descriptor, until either it determines the order or it runs out of descriptors.

So, when you sort your array, NSArray starts with the first key, i.e. @"name". If your VBAnimal class isn't KVC compliant for the key @"name", then you'll get the error above. There are at least three ways to implement key value coding for a given key:

  • provide a method with a name that matches the key and have it return a value
  • add a property with a name that matches the key
  • implement valueForKey: such that it returns a value for the key

You need to do one of those two for your VBAnimal class.

Upvotes: 1

Related Questions